Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ The JWT overload binds `Authentication:Jwt` to the selected scheme only. For exa

Actions alone remain supported. Defaults are supplied by each options type; configuration binding runs before callbacks; standard Options post-configuration runs afterward; feature validation runs on application startup. External provider options bind JSON values while callbacks can set non-bindable mapper delegates. Keep credentials in user secrets, environment variables, or a secret manager.

Session issuance is selected explicitly. `.UseJwt(...)` registers the JWT session issuer along with the JWT provider. For cookie applications, configure a cookie authentication scheme and add `.AddCookieAuthenticationSessionIssuer(options => options.IsPersistent = true)`; persistence defaults to `false`. Do not register both issuers for one user type. Refresh and logout endpoints use the mode reported by this same issuer registration, independent of the default sign-in scheme. Refresh tokens remain opt-in through `.AddRefreshToken(...)`: JWT clients receive refresh token data in the response, while cookie clients receive an HttpOnly refresh-token cookie.

Account operations, JWT creation, refresh-token operations, and external HTTP validation accept cancellation tokens where their dependencies support them. ASP.NET Core Identity user-store and sign-in APIs used for account lookup and credential checks do not expose cancellation-token overloads, so cancellation cannot interrupt those calls once started.

Applications upgrading from earlier releases should add exactly one issuer registration. JWT applications using `.UseJwt(...)` receive the JWT issuer automatically. Cookie applications should add `.AddCookieAuthenticationSessionIssuer(...)` and ensure its configured scheme matches the cookie scheme registered with ASP.NET Core.

Applications implementing `IUserAccountService<TUser>`, `IJwtProvider<TUser>`, or `IExternalLoginProvider<TUser>` directly should add the new optional cancellation-token parameter(s). Applications supplying a custom `IAuthenticationSessionIssuer<TUser>` must also set its `Mode` to `Jwt` or `Cookie` for refresh/logout endpoints. Existing call sites can omit cancellation tokens; ASP.NET Core Identity calls that do not accept tokens remain non-cancellable once started.

Registrations use `TryAdd` to preserve application-provided services. Store interfaces for a single store implementation resolve the same scoped store instance. Use `AddUserMapper` to replace the selected mapper; register custom store interfaces before `AddStores` to retain your implementations. Repeating feature registration appends options configuration in call order and does not duplicate default provider/service registrations.

In many cases you want to add social login to your project, so users can quickly log in and use the application. External login needs to redirect the user to the social login pages which are not useful for API services. This repository provides an easy way to handle external login in ASP.Net core web API. You only should do:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> UseJwt<TUser,
builder.Services.AddOptions<JwtBearerOptions>(scheme).ValidateOnStart();
builder.Authentication.AddJwtBearer(scheme, configure);
AddJwtProvider<TUser, TRole, TKey>(builder, scheme);
builder.AddJwtAuthenticationSessionIssuer();
return builder;
}

Expand All @@ -97,9 +98,35 @@ public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> UseJwt<TUser,
if (configure != null) schemeOptions.Configure(configure);
schemeOptions.ValidateOnStart();
AddJwtProvider<TUser, TRole, TKey>(builder, scheme);
builder.AddJwtAuthenticationSessionIssuer();
return builder;
}

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddJwtAuthenticationSessionIssuer<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder);
if(!RegisterSessionIssuer<TUser, RuntimeApps.Authentication.Features.Account.Services.JwtAuthenticationSessionIssuer<TUser, TKey>>(builder.Services)) return builder;
builder.Services.AddScoped<RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer<TUser>, RuntimeApps.Authentication.Features.Account.Services.JwtAuthenticationSessionIssuer<TUser, TKey>>();
return builder;
}

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddCookieAuthenticationSessionIssuer<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, Action<RuntimeApps.Authentication.Features.Account.Models.CookieSessionOptions> configure = null)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder);
if(!RegisterSessionIssuer<TUser, RuntimeApps.Authentication.Features.Account.Services.CookieAuthenticationSessionIssuer<TUser, TKey>>(builder.Services)) return builder;
builder.Services.AddOptions<RuntimeApps.Authentication.Features.Account.Models.CookieSessionOptions>();
if(configure != null) builder.Services.Configure(configure);
builder.Services.AddScoped<RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer<TUser>, RuntimeApps.Authentication.Features.Account.Services.CookieAuthenticationSessionIssuer<TUser, TKey>>();
return builder;
}

private static bool RegisterSessionIssuer<TUser, TIssuer>(IServiceCollection services) where TUser : class {
var existing = services.LastOrDefault(d => d.ServiceType == typeof(RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer<TUser>));
if(existing == null) return true;
if(existing.ImplementationType == typeof(TIssuer)) return false;
throw new InvalidOperationException("A conflicting authentication session issuer is already registered for this user type.");
}

private static void AddJwtProvider<TUser, TRole, TKey>(RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, string scheme)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> =>
builder.Services.TryAddScoped<IJwtProvider<TUser>>(services => new JwtProvider<TUser, TKey>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@ public static IEndpointRouteBuilder MapLoginApi<TUser, TUserDto, TKey>(this IEnd

IEnumerable<IExternalLoginProvider<TUser>> externalLoginProviders = endpoints.ServiceProvider.GetServices<IExternalLoginProvider<TUser>>();

routeGroup.MapPost("login", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> ([FromBody] UserLoginModel userLoginModel, IUserAccountService<TUser> userAccountService, [FromServices] IUserMapper<TUser, TUserDto> mapper) => {
var result = await userAccountService.LoginAsync(userLoginModel.UserName, userLoginModel.Password);
routeGroup.MapPost("login", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> ([FromBody] UserLoginModel userLoginModel, IUserAccountService<TUser> userAccountService, [FromServices] IUserMapper<TUser, TUserDto> mapper, HttpContext context) => {
var result = await userAccountService.LoginAsync(userLoginModel.UserName, userLoginModel.Password, context.RequestAborted);
if(!result.Succeeded)
return result.CreateValidationProblem();
return TypedResults.Ok(MapResult<TUser, TUserDto, TKey>(result, mapper));
});

if(externalLoginProviders?.Any() == true) {
routeGroup.MapPost("login/external", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService<TUser> userAccountService, [FromServices] IUserMapper<TUser, TUserDto> mapper) => {
var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token);
routeGroup.MapPost("login/external", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService<TUser> userAccountService, [FromServices] IUserMapper<TUser, TUserDto> mapper, HttpContext context) => {
var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token, context.RequestAborted);
if(!result.Succeeded)
return result.CreateValidationProblem();
return TypedResults.Ok(MapResult<TUser, TUserDto, TKey>(result, mapper));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
using RuntimeApps.Authentication.Features.RefreshTokens.Models;
using RuntimeApps.Authentication.Features.RefreshTokens.Services;
using RuntimeApps.Authentication.Features.Verification.Models;
using RuntimeApps.Authentication.Features.Account.Models;
using RuntimeApps.Authentication.Features.Account.Contracts;
using RuntimeApps.Authentication.Identity.Contracts;
namespace RuntimeApps.Authentication.Endpoints.RefreshTokens {
public static class RefreshTokenApiEndpointRouteBuilderExtensions {
Expand All @@ -20,24 +22,30 @@ public static class RefreshTokenApiEndpointRouteBuilderExtensions {
public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpointRouteBuilder endpoints)
where TUser : IdentityUser<TKey>
where TKey : IEquatable<TKey> {
if(endpoints.ServiceProvider.GetRequiredService<IServiceProviderIsService>()
.IsService(typeof(IAuthenticationSessionIssuer<TUser>)) != true)
throw new InvalidOperationException("Refresh-token endpoints require exactly one explicitly registered authentication session issuer.");

var routes = endpoints.MapGroup("");

routes.MapPost("refresh", async Task<IResult> (HttpContext context,
IUserManager<TUser> userManager,
IUserLockoutManager<TUser> lockoutManager,
IUserLoginManager<TUser> loginManager,
ISignInManager<TUser> signInManager,
IUserClaimsPrincipalFactory<TUser> principalFactory,
IRefreshTokenService<TKey> refreshTokenService,
IRefreshTokenRequestLimiter requestLimiter,
IServiceProvider services,
IAuthenticationSchemeProvider schemeProvider,
IAuthenticationHandlerProvider handlerProvider,
IEnumerable<IAuthenticationSessionIssuer<TUser>> sessionIssuers,
IOptions<RefreshTokenOptions> options,
IOptions<CookieSessionOptions> cookieOptions,
IOptions<VerificationOptions> verificationOptions) => {
if(!await requestLimiter.IsAllowedAsync(context, context.RequestAborted))
return Results.StatusCode(StatusCodes.Status429TooManyRequests);

var isCookie = await HasCookieSignInHandlerAsync(context, schemeProvider, handlerProvider);
var mode = GetSessionMode(sessionIssuers);
var isCookie = mode == AuthenticationSessionMode.Cookie;
RefreshTokenRequest request = null;
if(!isCookie && context.Request.HasJsonContentType())
request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted);
Expand Down Expand Up @@ -70,7 +78,9 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi

try {
if(isCookie) {
await signInManager.SignInAsync(user, true);
var principal = await principalFactory.CreateAsync(user);
await context.SignInAsync(cookieOptions.Value.Scheme, principal,
new AuthenticationProperties { IsPersistent = cookieOptions.Value.IsPersistent });
AppendRefreshCookie(context, options.Value, session.RefreshToken, session.ExpiresAt);
return Results.NoContent();
}
Expand All @@ -81,7 +91,7 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi
return Results.Problem("JWT authentication is not configured.", statusCode: StatusCodes.Status500InternalServerError);
}

var accessToken = await jwtProvider.GenerateTokenAsync(user);
var accessToken = await jwtProvider.GenerateTokenAsync(user, context.RequestAborted);
accessToken.RefreshToken = session.RefreshToken;
accessToken.RefreshTokenExpireDate = session.ExpiresAt;
accessToken.SessionId = session.SessionId;
Expand All @@ -97,10 +107,10 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi

routes.MapPost("logout", async Task<IResult> (HttpContext context,
IRefreshTokenService<TKey> refreshTokenService,
IOptions<RefreshTokenOptions> options) => {
var isCookie = await HasCookieSignInHandlerAsync(context,
context.RequestServices.GetRequiredService<IAuthenticationSchemeProvider>(),
context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>());
IOptions<RefreshTokenOptions> options,
IOptions<CookieSessionOptions> cookieOptions,
IEnumerable<IAuthenticationSessionIssuer<TUser>> sessionIssuers) => {
var isCookie = GetSessionMode(sessionIssuers) == AuthenticationSessionMode.Cookie;
RefreshTokenRequest request = null;
if(!isCookie && context.Request.HasJsonContentType())
request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted);
Expand All @@ -112,13 +122,9 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi
: request?.RefreshToken;
await refreshTokenService.RevokeAsync(token, context.RequestAborted);
if(isCookie)
await context.SignOutAsync();
context.Response.Cookies.Delete(options.Value.CookieName, new CookieOptions {
Path = options.Value.CookiePath,
Secure = options.Value.CookieSecure,
HttpOnly = true,
SameSite = options.Value.CookieSameSite
});
await context.SignOutAsync(cookieOptions.Value.Scheme);
if(isCookie)
DeleteRefreshCookie(context, options.Value);
return Results.NoContent();
})
.Accepts<RefreshTokenRequest>(true, "application/json")
Expand All @@ -128,44 +134,44 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi
routes.MapPost("logout/all", async Task<IResult> (HttpContext context,
IUserManager<TUser> userManager,
IRefreshTokenService<TKey> refreshTokenService,
IOptions<RefreshTokenOptions> options) => {
IOptions<RefreshTokenOptions> options,
IOptions<CookieSessionOptions> cookieOptions,
IEnumerable<IAuthenticationSessionIssuer<TUser>> sessionIssuers) => {
var isCookie = GetSessionMode(sessionIssuers) == AuthenticationSessionMode.Cookie;
var user = await userManager.GetUserAsync(context.User);
if(user == null)
return Results.Unauthorized();

var isCookie = await HasCookieSignInHandlerAsync(context,
context.RequestServices.GetRequiredService<IAuthenticationSchemeProvider>(),
context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>());
if(isCookie && !IsAllowedOrigin(context, options.Value))
return Results.StatusCode(StatusCodes.Status403Forbidden);

await refreshTokenService.RevokeAllAsync(user.Id, context.RequestAborted);
if(isCookie)
await context.SignOutAsync();
context.Response.Cookies.Delete(options.Value.CookieName, new CookieOptions {
Path = options.Value.CookiePath,
Secure = options.Value.CookieSecure,
HttpOnly = true,
SameSite = options.Value.CookieSameSite
});
await context.SignOutAsync(cookieOptions.Value.Scheme);
if(isCookie)
DeleteRefreshCookie(context, options.Value);
return Results.NoContent();
}).RequireAuthorization();

return endpoints;
}

private static async Task<bool> HasCookieSignInHandlerAsync(
HttpContext context,
IAuthenticationSchemeProvider schemeProvider,
IAuthenticationHandlerProvider handlerProvider) {
var scheme = await schemeProvider.GetDefaultSignInSchemeAsync();
if(scheme == null)
return false;

var handler = await handlerProvider.GetHandlerAsync(context, scheme.Name);
return handler is IAuthenticationSignInHandler;
private static AuthenticationSessionMode GetSessionMode<TUser>(IEnumerable<IAuthenticationSessionIssuer<TUser>> issuers) where TUser : class {
var registered = issuers.Take(2).ToArray();
if(registered.Length != 1)
throw new InvalidOperationException("Refresh-token endpoints require exactly one explicitly registered authentication session issuer.");
if(registered[0].Mode is not (AuthenticationSessionMode.Jwt or AuthenticationSessionMode.Cookie))
throw new InvalidOperationException("The registered authentication session issuer must explicitly select JWT or cookie mode.");
return registered[0].Mode;
}

private static void DeleteRefreshCookie(HttpContext context, RefreshTokenOptions options) => context.Response.Cookies.Delete(options.CookieName, new CookieOptions {
Path = options.CookiePath,
Secure = options.CookieSecure,
HttpOnly = true,
SameSite = options.CookieSameSite
});

private static bool IsAllowedOrigin(HttpContext context, RefreshTokenOptions options) {
var origin = context.Request.Headers["Origin"].ToString();
if(!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using RuntimeApps.Authentication.Shared.Models;

namespace RuntimeApps.Authentication.Features.Account.Contracts {
public enum AuthenticationSessionMode {
Unspecified = 0,
Jwt = 1,
Cookie = 2
}

/// <summary>Establishes an authentication session for an account that has already passed eligibility checks.</summary>
public interface IAuthenticationSessionIssuer<TUser> where TUser : class {
/// <summary>Identifies the explicitly registered mechanism used by refresh and logout operations.</summary>
AuthenticationSessionMode Mode => AuthenticationSessionMode.Unspecified;
Task<Token> IssueAsync(TUser user, CancellationToken cancellationToken = default);
}
}
Loading
Loading