MasLazu.AspNet.Authentication.Password.Abstraction 1.0.0-preview.12

This is a prerelease version of MasLazu.AspNet.Authentication.Password.Abstraction.
dotnet add package MasLazu.AspNet.Authentication.Password.Abstraction --version 1.0.0-preview.12
                    
NuGet\Install-Package MasLazu.AspNet.Authentication.Password.Abstraction -Version 1.0.0-preview.12
                    
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="MasLazu.AspNet.Authentication.Password.Abstraction" Version="1.0.0-preview.12" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MasLazu.AspNet.Authentication.Password.Abstraction" Version="1.0.0-preview.12" />
                    
Directory.Packages.props
<PackageReference Include="MasLazu.AspNet.Authentication.Password.Abstraction" />
                    
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 MasLazu.AspNet.Authentication.Password.Abstraction --version 1.0.0-preview.12
                    
#r "nuget: MasLazu.AspNet.Authentication.Password.Abstraction, 1.0.0-preview.12"
                    
#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 MasLazu.AspNet.Authentication.Password.Abstraction@1.0.0-preview.12
                    
#: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=MasLazu.AspNet.Authentication.Password.Abstraction&version=1.0.0-preview.12&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=MasLazu.AspNet.Authentication.Password.Abstraction&version=1.0.0-preview.12&prerelease
                    
Install as a Cake Tool

MasLazu.AspNet.Authentication.Password.Abstraction

A clean, secure, and extensible abstraction layer for password-based authentication in ASP.NET applications.

Overview

This package provides the core abstractions and data models for implementing password-based authentication in ASP.NET applications. It defines interfaces, request/response models, and DTOs that form the foundation of a robust authentication system.

Features

  • 🔐 Secure Password Handling: Passwords are never stored in plain text
  • 🏗️ Clean Architecture: Separation of concerns with clear abstraction layers
  • 🔄 Async/Await Support: All operations support asynchronous programming with cancellation tokens
  • 🎯 Flexible Authentication: Supports multiple authentication methods per user
  • 📊 Activity Tracking: Tracks login activity for security monitoring
  • 🛡️ Type Safety: Uses C# records and nullable reference types for compile-time safety
  • 🔗 Framework Integration: Built on top of MasLazu.AspNet.Framework.Application

Installation

dotnet add package MasLazu.AspNet.Authentication.Password.Abstraction

Core Interface

IUserPasswordLoginService

The main interface that defines the contract for password authentication operations:

public interface IUserPasswordLoginService : ICrudService<UserPasswordLoginDto, CreateUserPasswordLoginRequest, UpdateUserPasswordLoginRequest>
{
    Task<PasswordLoginResponse> LoginAsync(PasswordLoginRequest request, CancellationToken ct);
    Task RegisterAsync(PasswordRegisterRequest request, CancellationToken ct);
    Task ChangePasswordAsync(Guid userId, ChangePasswordRequest request, CancellationToken ct);
}

Data Models

Authentication Models

PasswordLoginRequest

Request model for user login:

public record PasswordLoginRequest(
    string Identifier,  // Email or username
    string Password
);
PasswordRegisterRequest

Request model for user registration:

public record PasswordRegisterRequest(
    string Name,
    string Username,
    string Email,
    string Password
);
ChangePasswordRequest

Request model for password changes:

public record ChangePasswordRequest(
    string CurrentPassword,
    string NewPassword
);
PasswordLoginResponse

Response model containing authentication tokens:

public record PasswordLoginResponse(
    string AccessToken,
    string RefreshToken,
    DateTimeOffset AccessTokenExpiresAt,
    DateTimeOffset RefreshTokenExpiresAt,
    string TokenType = "Bearer"
);

Data Transfer Objects

UserPasswordLoginDto

Main DTO representing a user's password login information:

public record UserPasswordLoginDto(
    Guid Id,
    Guid UserLoginMethodId,
    string PasswordHash,
    DateTime? LastLoginDate,
    DateTimeOffset CreatedAt,
    DateTimeOffset? UpdatedAt
) : BaseDto(Id, CreatedAt, UpdatedAt);
CRUD Operation Models

CreateUserPasswordLoginRequest:

public record CreateUserPasswordLoginRequest(
    Guid UserLoginMethodId,
    string PasswordHash  // Already hashed
);

UpdateUserPasswordLoginRequest:

public record UpdateUserPasswordLoginRequest(
    Guid Id,
    Guid? UserLoginMethodId,
    string? PasswordHash,
    DateTime? LastLoginDate
) : BaseUpdateRequest(Id);

Quick Start

Basic Usage

// Register the service
services.AddScoped<IUserPasswordLoginService, YourPasswordLoginService>();

// Use in controller
[HttpPost("login")]
public async Task<IActionResult> Login(PasswordLoginRequest request)
{
    var response = await _authService.LoginAsync(request, CancellationToken.None);
    return Ok(response);
}

Usage Example

Implementing the Service

public class UserPasswordLoginService : IUserPasswordLoginService
{
    private readonly IPasswordHasher _passwordHasher;
    private readonly IUserRepository _userRepository;
    private readonly IJwtTokenGenerator _jwtGenerator;

    public async Task<PasswordLoginResponse> LoginAsync(PasswordLoginRequest request, CancellationToken ct)
    {
        // Find user by identifier (email/username)
        var user = await _userRepository.FindByIdentifierAsync(request.Identifier, ct);
        if (user == null)
            throw new UnauthorizedAccessException("Invalid credentials");

        // Verify password
        var isValidPassword = _passwordHasher.VerifyPassword(request.Password, user.PasswordHash);
        if (!isValidPassword)
            throw new UnauthorizedAccessException("Invalid credentials");

        // Generate tokens
        var tokens = await _jwtGenerator.GenerateTokensAsync(user, ct);

        // Update last login date
        await UpdateLastLoginDateAsync(user.Id, ct);

        return new PasswordLoginResponse(
            tokens.AccessToken,
            tokens.RefreshToken,
            tokens.AccessTokenExpiresAt,
            tokens.RefreshTokenExpiresAt
        );
    }

    // Implement other interface methods...
}

Registering in DI Container

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IUserPasswordLoginService, UserPasswordLoginService>();
    services.AddScoped<IPasswordHasher, BcryptPasswordHasher>();
    services.AddScoped<IJwtTokenGenerator, JwtTokenGenerator>();
}

Using in Controller

[ApiController]
[Route("api/auth")]
public class AuthenticationController : ControllerBase
{
    private readonly IUserPasswordLoginService _authService;

    public AuthenticationController(IUserPasswordLoginService authService)
    {
        _authService = authService;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(PasswordLoginRequest request)
    {
        try
        {
            var response = await _authService.LoginAsync(request, CancellationToken.None);
            return Ok(response);
        }
        catch (UnauthorizedAccessException)
        {
            return Unauthorized("Invalid credentials");
        }
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(PasswordRegisterRequest request)
    {
        await _authService.RegisterAsync(request, CancellationToken.None);
        return Ok("User registered successfully");
    }

    [HttpPost("change-password")]
    [Authorize]
    public async Task<IActionResult> ChangePassword(ChangePasswordRequest request)
    {
        var userId = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
        await _authService.ChangePasswordAsync(userId, request, CancellationToken.None);
        return Ok("Password changed successfully");
    }
}

Security Best Practices

  1. Password Hashing: Always hash passwords before storage using strong algorithms like bcrypt or Argon2
  2. Salt Usage: Use unique salts for each password
  3. Token Security: Implement proper JWT token validation and refresh token rotation
  4. Rate Limiting: Implement rate limiting on authentication endpoints
  5. Audit Logging: Log authentication attempts for security monitoring
  6. Password Policies: Enforce strong password requirements
  7. Account Lockout: Implement temporary account lockout after failed attempts

Dependencies

  • Target Framework: .NET 9.0
  • MasLazu.AspNet.Framework.Application: ^1.0.0-preview.6

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

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

  • MasLazu.AspNet.Authentication.Password: Main implementation package
  • MasLazu.AspNet.Authentication.Password.Domain: Domain entities and business logic
  • MasLazu.AspNet.Authentication.Password.EfCore: Entity Framework Core implementation
  • MasLazu.AspNet.Authentication.Password.Endpoint: Minimal API endpoints</content> <parameter name="filePath">/home/mfaziz/projects/cs/MasLazu.AspNet.Authentication.Password/src/MasLazu.AspNet.Authentication.Password.Abstraction/README.md
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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 (2)

Showing the top 2 NuGet packages that depend on MasLazu.AspNet.Authentication.Password.Abstraction:

Package Downloads
MasLazu.AspNet.Authentication.Password

Application layer for MasLazu ASP.NET Password Authentication. Contains service implementations, validation, and business logic.

MasLazu.AspNet.Authentication.Password.Endpoint

Endpoint layer for MasLazu ASP.NET Password Authentication. Contains REST API endpoints using FastEndpoints framework.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0-preview.12 146 10/8/2025
1.0.0-preview.11 138 10/8/2025
1.0.0-preview.10 132 10/8/2025
1.0.0-preview.9 144 10/1/2025
1.0.0-preview.8 139 10/1/2025
1.0.0-preview.7 138 10/1/2025
1.0.0-preview.5 142 10/1/2025
1.0.0-preview.4 143 9/29/2025
1.0.0-preview.3 234 9/19/2025
1.0.0-preview.1 231 9/19/2025