Skip to content

stackworx-dotnet/Stackworx.AspNetCore

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Stackworx.AspNetCore.DevTools

ASP.NET Core developer tools for local development workflows: token-based one-click authentication, configurable sign-in callbacks, local configuration file injection, and login URL helpers.

For development use only. None of the APIs in this package should be registered or reachable in production environments.

Installation

dotnet add package Stackworx.AspNetCore.DevTools

Or add it directly to your .csproj:

<PackageReference Include="Stackworx.AspNetCore.DevTools" Version="1.0.0" />

Features


Token-Based Dev Auth

DevelopmentAuthTokenMiddleware intercepts requests to a configured login path that carry a ?t=<token> query parameter. On a valid token it invokes your sign-in callback and redirects; on an invalid token it strips the parameter and continues.

The token is generated fresh on every application start using RandomNumberGenerator, and validated with CryptographicOperations.FixedTimeEquals to prevent timing attacks.

Registration

if (builder.Environment.IsDevelopment())
{
    builder.Services.AddDevelopmentAuth(opts =>
    {
        // Required: provide your own sign-in logic using the request-scoped IServiceProvider.
        opts.OnSignInAsync = async sp =>
        {
            var signInService = sp.GetRequiredService<MySignInService>();
            await signInService.SignInAsync();
        };

        // Optional: override the login path (default: /account/login)
        opts.LoginPath = "/auth/dev-login";
    });

    builder.Services.AddScoped<MySignInService>();
}

Add the middleware to the pipeline before UseAuthentication:

if (app.Environment.IsDevelopment())
{
    app.UseMiddleware<DevelopmentAuthTokenMiddleware>();
}

app.UseAuthentication();
app.UseAuthorization();

The middleware uses context.RequestServices (the per-request scope), so scoped services such as SignInManager<T> are resolved correctly.

Logging the login URL

After building the app, read the token from DevelopmentAuthTokenProvider and build the full URL:

if (app.Environment.IsDevelopment())
{
    var tokenProvider = app.Services.GetRequiredService<DevelopmentAuthTokenProvider>();
    var loginUrl = DevelopmentAuthLoginUrlBuilder.Build(tokenProvider.Token);
    app.Logger.LogInformation("Dev login: {LoginUrl}", loginUrl);
}

Open the logged URL in a browser to sign in instantly—no credentials needed.


Configurable Sign-In Callback

The OnSignInAsync delegate receives the request-scoped IServiceProvider, giving you full control over how the development user is signed in:

builder.Services.AddDevelopmentAuth(opts =>
{
    opts.OnSignInAsync = async sp =>
    {
        var userManager = sp.GetRequiredService<UserManager<ApplicationUser>>();
        var signInManager = sp.GetRequiredService<SignInManager<ApplicationUser>>();

        var user = await userManager.FindByEmailAsync("dev@example.com")
            ?? throw new InvalidOperationException("Dev user not found.");

        await signInManager.SignInAsync(user, isPersistent: false);
    };
});

Auto-User Customization

If your sign-in service auto-creates users that don't exist, expose an Action<TUser> callback in your service options and invoke it before persisting the new user:

// In your app's sign-in service options
public sealed class MySignInOptions
{
    public Action<ApplicationUser>? ConfigureUser { get; set; }
}

// In your sign-in service
private async Task<ApplicationUser> AutoRegisterAsync(string email)
{
    var newUser = new ApplicationUser { Email = email, UserName = email };
    _options.Value.ConfigureUser?.Invoke(newUser);  // apply customization
    await _userManager.CreateAsync(newUser);
    return newUser;
}

Register the callback in Program.cs:

builder.Services.AddOptions<MySignInOptions>().Configure(opts =>
{
    opts.ConfigureUser = user =>
    {
        user.DisplayName = "Local Developer";
        // assign roles, tenant IDs, etc.
    };
});

JSON Config File Injection

AddJsonFileAfterLastJsonFile inserts a JSON configuration source immediately after the last existing JSON source (typically appsettings.[Environment].json). This lets a local override file take priority over the environment file without disrupting the standard ASP.NET Core configuration order.

if (builder.Environment.IsDevelopment())
{
    builder.Configuration.AddJsonFileAfterLastJsonFile(
        path: "appsettings.Local.json",
        optional: true,
        reloadOnChange: false);
}

appsettings.Local.json is typically .gitignored and holds developer-specific secrets and connection strings.


Dev Login URL Builder

DevelopmentAuthLoginUrlBuilder.Build reads ASPNETCORE_URLS, prefers HTTPS, normalises wildcard hosts (+, *, 0.0.0.0) to localhost, and returns a ready-to-open URL:

var url = DevelopmentAuthLoginUrlBuilder.Build(token);
// e.g. https://localhost:5001/account/login?t=3f8a...

// With a custom login path:
var url = DevelopmentAuthLoginUrlBuilder.Build(token, loginPath: "/auth/dev-login");

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages