CodeWorks.Auth 0.0.5

There is a newer version of this package available.
See the version list below for details.
dotnet add package CodeWorks.Auth --version 0.0.5
                    
NuGet\Install-Package CodeWorks.Auth -Version 0.0.5
                    
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="CodeWorks.Auth" Version="0.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CodeWorks.Auth" Version="0.0.5" />
                    
Directory.Packages.props
<PackageReference Include="CodeWorks.Auth" />
                    
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 CodeWorks.Auth --version 0.0.5
                    
#r "nuget: CodeWorks.Auth, 0.0.5"
                    
#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 CodeWorks.Auth@0.0.5
                    
#: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=CodeWorks.Auth&version=0.0.5
                    
Install as a Cake Addin
#tool nuget:?package=CodeWorks.Auth&version=0.0.5
                    
Install as a Cake Tool

AuthModule

A highly flexible, pluggable authentication module for .NET APIs that supports:

  • JWT bearer token authentication
  • Email/password login with secure hashing
  • Role and permission-based authorization via [Authorize] and [HasPermission]
  • Email verification workflows
  • Magic link login support
  • Abstracted storage and email services for full control

Features

  • Storage-agnostic: Bring your own User, UserStore, TokenStore, and EmailSender
  • Secure by default: Uses ASP.NET Core Identity's password hasher and JWT best practices
  • Policy-based authorization: Out of the box support for roles and custom permissions
  • Plug-and-play email auth: Verification and magic link flows supported
  • Ready for NuGet packaging

Installation

Add the package (once published):

Install-Package CodeWorks.Auth

Getting Started

1. Define Your User

public class AppUser : IUser
{
    public string Id { get; set; }
    public string Email { get; set; }
    public string PasswordHash { get; set; }
    public bool IsEmailVerified { get; set; }
    public IEnumerable<string> Roles { get; set; }
    public IEnumerable<string> Permissions { get; set; }
}

2. Implement Required Interfaces

IUserStore<TUser>

Manages user persistence (load/save/verify).

IUserTokenStore

Manages tokens used for email verification or magic login.

IUserEmailSender

Sends emails to users with custom logic (SMTP, SendGrid, etc.).

3. Register the Module

services.AddAuthModule<AppUser, AppUserStore>(options =>
{
    options.SigningKey = Configuration["Jwt:Key"];
    options.Issuer = "your-api";
    options.Audience = "your-users";
    options.Expiration = TimeSpan.FromHours(1);
},
new[] { "CanViewReports", "CanDeleteUsers" });

Services.AddOAuthProviders(builder.Configuration);
Services.AddScoped<IOAuthService<AppUser>, OAuthService<AppUser>>();

Usage

Login and Registration

Use IAuthService<TUser>:

await authService.RegisterAsync(user, password);
await authService.LoginAsync(email, password);

Use EmailAuthService<TUser>:

await emailAuth.RequestVerificationEmailAsync(user, "https://your.site/verify");
await emailAuth.ConfirmEmailAsync(token);

await emailAuth.RequestMagicLinkAsync(email, "https://your.site/login");
await emailAuth.RedeemMagicLinkAsync(token);

Authorization

Roles

[Authorize(Roles = "Admin")]

Permissions

[HasPermission("CanDeleteUsers")]

Email Setup

Development

For local development, use a simple log-based sender:

public class DevEmailSender : IUserEmailSender
{
    private readonly ILogger<DevEmailSender> _logger;

    public DevEmailSender(ILogger<DevEmailSender> logger)
    {
        _logger = logger;
    }

    public Task SendVerificationEmailAsync(IUser user, string tokenUrl)
    {
        _logger.LogInformation($"[DEV] Verification link for {user.Email}: {tokenUrl}");
        return Task.CompletedTask;
    }

    public Task SendMagicLinkAsync(IUser user, string tokenUrl)
    {
        _logger.LogInformation($"[DEV] Magic login link for {user.Email}: {tokenUrl}");
        return Task.CompletedTask;
    }
}

Register it conditionally:

if (env.IsDevelopment())
{
    services.AddScoped<IUserEmailSender, DevEmailSender>();
}

AuthController Example

[ApiController]
[Route("api/auth")]
public class OAuthController<TUser> : ControllerBase 
    where TUser : IOAuthUser, new()
{
    private readonly IOAuthService<TUser> _oauthService;
    private readonly SignInManager<TUser> _signInManager;

    public OAuthController(
        IOAuthService<TUser> oauthService,
        SignInManager<TUser> signInManager)
    {
        _oauthService = oauthService;
        _signInManager = signInManager;
    }

    [HttpGet("google")]
    public IActionResult GoogleLogin(string returnUrl = "/")
    {
        var redirectUrl = Url.Action(
            nameof(GoogleCallback), 
            new { returnUrl });
        
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(
            "Google", 
            redirectUrl);
        
        return Challenge(properties, "Google");
    }

    [HttpGet("google/callback")]
    public async Task<IActionResult> GoogleCallback(string returnUrl = "/")
    {
        var info = await _signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return BadRequest(new { error = "Error loading external login info" });
        }

        var result = await _oauthService.HandleOAuthCallbackAsync(info);
        
        if (!result.Success)
        {
            return BadRequest(new { error = result.ErrorMessage });
        }

        // Return token to client
        return Ok(new
        {
            token = result.Token,
            user = new
            {
                result.User.Id,
                result.User.Email,
                result.User.Roles,
                result.User.ProfilePictureUrl
            }
        });
    }

    [HttpGet("facebook")]
    public IActionResult FacebookLogin(string returnUrl = "/")
    {
        var redirectUrl = Url.Action(
            nameof(FacebookCallback), 
            new { returnUrl });
        
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(
            "Facebook", 
            redirectUrl);
        
        return Challenge(properties, "Facebook");
    }

    [HttpGet("facebook/callback")]
    public async Task<IActionResult> FacebookCallback(string returnUrl = "/")
    {
        var info = await _signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return BadRequest(new { error = "Error loading external login info" });
        }

        var result = await _oauthService.HandleOAuthCallbackAsync(info);
        
        if (!result.Success)
        {
            return BadRequest(new { error = result.ErrorMessage });
        }

        return Ok(new
        {
            token = result.Token,
            user = new
            {
                result.User.Id,
                result.User.Email,
                result.User.Roles,
                result.User.ProfilePictureUrl
            }
        });
    }
}

OAuth State Store

You will want some implementation of State Store for OAuth callbacks. There are two services based on need you can use an InMemory or DistributedCache. Both implement the same IOAuthStateStore as in the example below if you prefer something more like using your own DB.

/// <summary>
/// Database implementation for OAuth state store
/// Best for persistence and audit trail requirements
/// </summary>
public class DatabaseOAuthStateStore : IOAuthStateStore
{
    private readonly IDbConnection _db;
    private readonly ILogger<DatabaseOAuthStateStore> _logger;

    public DatabaseOAuthStateStore(
        IDbConnection db,
        ILogger<DatabaseOAuthStateStore> logger)
    {
        _db = db;
        _logger = logger;
    }

    public async Task StoreStateAsync(OAuthState state)
    {
        const string sql = @"
            INSERT INTO oauth_states (token, provider, return_url, created_at, expires_at, is_used)
            VALUES (@Token, @Provider, @ReturnUrl, @CreatedAt, @ExpiresAt, @IsUsed)";

        await _db.ExecuteAsync(sql, state);
        _logger.LogDebug("Stored OAuth state in database: {Token}", state.Token);
    }

    public async Task<OAuthState?> GetStateAsync(string token)
    {
        const string sql = @"
            SELECT token, provider, return_url as ReturnUrl, created_at as CreatedAt, 
                   expires_at as ExpiresAt, is_used as IsUsed
            FROM oauth_states 
            WHERE token = @token";

        return await _db.QueryFirstOrDefaultAsync<OAuthState>(sql, new { token });
    }

    public async Task UpdateStateAsync(OAuthState state)
    {
        const string sql = @"
            UPDATE oauth_states 
            SET is_used = @IsUsed, return_url = @ReturnUrl
            WHERE token = @Token";

        await _db.ExecuteAsync(sql, state);
        _logger.LogDebug("Updated OAuth state in database: {Token}", state.Token);
    }

    public async Task DeleteStateAsync(string token)
    {
        const string sql = "DELETE FROM oauth_states WHERE token = @token";
        await _db.ExecuteAsync(sql, new { token });
        _logger.LogDebug("Deleted OAuth state from database: {Token}", token);
    }

    public async Task CleanupExpiredStatesAsync()
    {
        const string sql = "DELETE FROM oauth_states WHERE expires_at < @now";
        var deletedCount = await _db.ExecuteAsync(sql, new { now = DateTime.UtcNow });

        if (deletedCount > 0)
        {
            _logger.LogInformation("Cleaned up {Count} expired OAuth states from database", deletedCount);
        }
    }
}

Production

Use a real SMTP service like MailKit to send actual emails. Here’s a starting point:

You can also configure third-party providers such as:

OAuth Provider Setup

  1. Install Required NuGet Packages:
dotnet add package Microsoft.AspNetCore.Authentication.Google
dotnet add package Microsoft.AspNetCore.Authentication.Facebook
  1. Add OAuth Configuration to appsettings.json
{
  "Authentication": {
    "Google": {
      "ClientId": "your-google-client-id",
      "ClientSecret": "your-google-client-secret"
    },
    "Facebook": {
      "AppId": "your-facebook-app-id",
      "AppSecret": "your-facebook-app-secret"
    }
  },
  "Jwt": {
    "Key": "your-signing-key",
    "Issuer": "your-api",
    "Audience": "your-users"
  }
}

Extensibility

  • IUser - your user model
  • IUserStore<TUser> - storage logic
  • IUserTokenStore - token persistence
  • IUserEmailSender - email transport

Roadmap

  • Multi-factor authentication
  • TOTP support

License

MIT or commercial dual-license (TBD).

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

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
0.2.0 179 2/27/2026
0.1.0 114 2/27/2026
0.0.9 482 11/18/2025
0.0.8 428 11/17/2025
0.0.7 316 11/13/2025
0.0.6 231 11/4/2025
0.0.5 226 10/30/2025
0.0.4 226 10/30/2025
0.0.3 226 10/28/2025
0.0.2 284 5/31/2025
0.0.1 242 4/21/2025