NcDanilo.UserLibrary 1.2.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package NcDanilo.UserLibrary --version 1.2.2
                    
NuGet\Install-Package NcDanilo.UserLibrary -Version 1.2.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NcDanilo.UserLibrary" Version="1.2.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NcDanilo.UserLibrary" Version="1.2.2" />
                    
Directory.Packages.props
<PackageReference Include="NcDanilo.UserLibrary" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NcDanilo.UserLibrary --version 1.2.2
                    
#r "nuget: NcDanilo.UserLibrary, 1.2.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NcDanilo.UserLibrary@1.2.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NcDanilo.UserLibrary&version=1.2.2
                    
Install as a Cake Addin
#tool nuget:?package=NcDanilo.UserLibrary&version=1.2.2
                    
Install as a Cake Tool

NcDanilo.UserLibrary

A .NET class library that provides ready-to-use services and repositories for user management, role management, and JWT-based authentication (access token + refresh token) backed by a SQL Server database.

NuGet License .NET


Table of Contents


Features

  • User management — create, read (by ID or email), update, soft-delete users.
  • Role management — create, read, update, soft-delete roles.
  • JWT access tokens — signed with HMAC-SHA256, expire after 15 minutes, carrying standard claims (id, email, given_name, surname, role).
  • Refresh tokens — persisted to SQL Server, expire after 7 days, support revocation.
  • Password hashing — passwords are securely hashed with BCrypt before storage.
  • Fully async — all I/O operations are async/await with CancellationToken support.
  • Interface-driven — every component is hidden behind an interface, making it easy to mock and test.

Target Frameworks

Framework Version
.NET 10.0

Installation

Install via the .NET CLI:

dotnet add package NcDanilo.UserLibrary

Or search for NcDanilo.UserLibrary in the Visual Studio NuGet Package Manager UI.


Configuration

The library reads its settings from an AppConfiguration object injected via IOptions<AppConfiguration>.

Property Description
ConnectionString SQL Server connection string
SecretKey Secret used to sign JWT tokens (≥ 32 characters recommended)
Issuer JWT iss claim value
Audience JWT aud claim value

appsettings.json example

{
  "AppConfiguration": {
    "ConnectionString": "Server=localhost;Database=MyDb;Trusted_Connection=True;",
    "SecretKey": "your-very-secret-key-at-least-32-chars",
    "Issuer": "https://yourapp.com",
    "Audience": "https://yourapp.com"
  }
}

Database Setup

The library expects the following tables to exist in your SQL Server database.

Roles

CREATE TABLE Roles (
    Id       UNIQUEIDENTIFIER PRIMARY KEY,
    Name     NVARCHAR(100)    NOT NULL,
    Status   INT              NOT NULL DEFAULT 0  -- 0 = Enabled, 1 = Disabled
);

Users

CREATE TABLE Users (
    Id          UNIQUEIDENTIFIER PRIMARY KEY,
    FirstName   NVARCHAR(100)    NOT NULL,
    LastName    NVARCHAR(100)    NOT NULL,
    Email       NVARCHAR(256)    NOT NULL UNIQUE,
    Password    NVARCHAR(512)    NOT NULL,  -- BCrypt hash
    Status      INT              NOT NULL DEFAULT 0,
    BirthDate   DATETIME2        NOT NULL,
    RoleId      UNIQUEIDENTIFIER NOT NULL REFERENCES Roles(Id)
);

RefreshTokens

CREATE TABLE RefreshTokens (
    Id          UNIQUEIDENTIFIER PRIMARY KEY,
    UserId      UNIQUEIDENTIFIER NOT NULL,
    Token       NVARCHAR(512)    NOT NULL,
    Expiration  DATETIME2        NOT NULL,
    IsRevoked   BIT              NOT NULL DEFAULT 0
);

Note: "Delete" operations on both Users and Roles are implemented as soft deletes — the Status column is set to 1 (Disabled) rather than removing the row.


Getting Started

Registering Services (Dependency Injection)

using Microsoft.Extensions.DependencyInjection;
using UserLibrary.Configuration;
using UserLibrary.Interface;
using UserLibrary.Repository;
using UserLibrary.Service;

var services = new ServiceCollection();

// Bind configuration
services.Configure<AppConfiguration>(
    builder.Configuration.GetSection("AppConfiguration"));

// Register repositories
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IRoleRepository, RoleRepository>();
services.AddScoped<IRefreshTokenRepository, RefreshTokenRepository>();

// Register services
services.AddScoped<IManageTokenService, ManageTokenService>();
services.AddScoped<IUserService, UserService>();

User Registration

var newUser = new UserDto
{
    FirstName = "John",
    LastName  = "Doe",
    Email     = "john.doe@example.com",
    Password  = "P@ssw0rd!",
    BirthDate = new DateTime(1990, 1, 1),
    Status    = Status.Enabled,
    Role      = new RoleDto { Id = existingRoleId }
};

UserDto registered = await userService.RegisterUser(newUser, CancellationToken.None);
// registered.Password is null — never returned after hashing

User Login

UserDto loggedIn = await userService.LoginUser(
    "john.doe@example.com",
    "P@ssw0rd!",
    CancellationToken.None);

Console.WriteLine(loggedIn.AccessToken.Token);       // JWT string
Console.WriteLine(loggedIn.AccessToken.Expiration);  // UTC +15 minutes
Console.WriteLine(loggedIn.RefreshToken.Token);      // Refresh token string

Throws UnauthorizedAccessException on invalid credentials or a bad refresh token.


Role Management

// Create
var role = new Role { Id = Guid.NewGuid(), RoleName = "Admin", Status = Status.Enabled };
bool created = await roleRepository.CreateRole(role, CancellationToken.None);

// Read
Role fetched = await roleRepository.GetRoleById(role.Id, CancellationToken.None);

// Update
fetched.RoleName = "SuperAdmin";
bool updated = await roleRepository.UpdateRole(fetched, CancellationToken.None);

// Soft-delete (sets Status = Disabled)
bool deleted = await roleRepository.DeleteRole(role.Id, CancellationToken.None);

Token Validation

bool isValid = await manageTokenService.ValidateRefreshToken(
    userDto.RefreshToken,
    CancellationToken.None);

Returns true only when the token exists in the database, has not been revoked, and has not expired.


Project Structure

UserLibrary/
├── Configuration/
│   └── AppConfiguration.cs       # Settings POCO (connection string, JWT params)
├── Dto/
│   ├── UserDto.cs                 # User data transfer object
│   └── RoleDto.cs                 # Role data transfer object
├── Interface/
│   ├── IUserRepository.cs
│   ├── IRoleRepository.cs
│   ├── IRefreshTokenRepository.cs
│   ├── IUserService.cs
│   └── IManageTokenService.cs
├── Model/
│   ├── User.cs
│   ├── Role.cs
│   ├── AccessToken.cs
│   ├── RefreshToken.cs
│   └── Status.cs                  # Enum: Enabled = 0, Disabled = 1
├── Repository/
│   ├── UserRepository.cs
│   ├── RoleRepository.cs
│   └── RefreshTokenRepository.cs
├── Service/
│   ├── UserService.cs
│   └── ManageTokenService.cs
└── TokenHelper.cs                 # JWT generation utility

Models & DTOs

User / UserDto

Property Type Notes
Id Guid Auto-generated on registration
FirstName string
LastName string
Email string Used as login identifier
Password string BCrypt hashed; null in responses
BirthDate DateTime
Status Status Enabled or Disabled
Role Role/RoleDto Associated role
AccessToken AccessToken Populated after login
RefreshToken RefreshToken Populated after login

AccessToken

Property Type Notes
Token string JWT string
Expiration DateTime UTC, 15 minutes from issue

RefreshToken

Property Type Notes
Id Guid
UserId Guid
Token string GUID-based opaque string
Expiration DateTime UTC, 7 days from issue
IsRevoked bool

Interfaces

Interface Responsibility
IUserRepository CRUD operations on the Users table
IRoleRepository CRUD operations on the Roles table
IRefreshTokenRepository Persist and validate refresh tokens
IUserService High-level register / login flow
IManageTokenService Generate and validate access & refresh tokens

Dependencies

Package Version Notes
BCrypt.Net-Next 4.1.0 Password hashing
Microsoft.Data.SqlClient 7.0.0 SQL Server connectivity
Newtonsoft.Json 13.0.4 JSON serialization
Microsoft.AspNetCore.App (framework ref) ASP.NET Core integration

License

This project is licensed under the MIT License — see LICENSE for details.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.3 114 3/27/2026
1.2.2 98 3/26/2026
1.2.1 97 3/25/2026
1.2.0 96 3/25/2026
1.1.3 94 3/25/2026
1.1.2 98 3/24/2026
1.1.1 95 3/24/2026
1.1.0 101 3/24/2026
1.0.10 113 3/24/2026
1.0.9 95 3/23/2026
1.0.7 96 3/23/2026
1.0.6 97 3/23/2026
1.0.5 99 3/23/2026
1.0.4 94 3/23/2026
1.0.3 100 3/23/2026
1.0.2 98 3/23/2026
1.0.1 99 3/23/2026
1.0.0 97 3/23/2026