From 52f29aec871b7b6e36da9166228b73fe50f1234b Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 12:31:30 +0100 Subject: [PATCH 1/4] [AMI-133] Separate account and session issuance --- ReadMe.md | 4 + .../FeatureRegistrationExtensions.cs | 25 +++++ .../Contracts/IAuthenticationSessionIssuer.cs | 8 ++ .../Account/Models/CookieSessionOptions.cs | 6 ++ .../CookieAuthenticationSessionIssuer.cs | 34 +++++++ .../JwtAuthenticationSessionIssuer.cs | 31 +++++++ .../Account/Services/UserAccountService.cs | 91 +++++-------------- .../Identity/Contracts/ISignInManager.cs | 1 + .../Identity/RuntimeAppsSignInManager.cs | 5 +- .../Program.cs | 5 +- 10 files changed, 137 insertions(+), 73 deletions(-) create mode 100644 RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs create mode 100644 RuntimeApps.Authentication/Features/Account/Models/CookieSessionOptions.cs create mode 100644 RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs create mode 100644 RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs diff --git a/ReadMe.md b/ReadMe.md index 98cde67..18337b1 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -109,6 +109,10 @@ 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 tokens remain opt-in through `.AddRefreshToken(...)`: JWT clients receive refresh token data in the response, while cookie clients receive an HttpOnly refresh-token cookie. + +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. + 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: diff --git a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs index 61f4df3..18b0064 100644 --- a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs +++ b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs @@ -85,6 +85,7 @@ public static RuntimeAppsAuthenticationBuilder UseJwt(scheme).ValidateOnStart(); builder.Authentication.AddJwtBearer(scheme, configure); AddJwtProvider(builder, scheme); + builder.AddJwtAuthenticationSessionIssuer(); return builder; } @@ -97,9 +98,33 @@ public static RuntimeAppsAuthenticationBuilder UseJwt(builder, scheme); + builder.AddJwtAuthenticationSessionIssuer(); return builder; } + public static RuntimeAppsAuthenticationBuilder AddJwtAuthenticationSessionIssuer(this RuntimeAppsAuthenticationBuilder builder) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + EnsureNoSessionIssuer(builder.Services); + builder.Services.AddScoped, RuntimeApps.Authentication.Features.Account.Services.JwtAuthenticationSessionIssuer>(); + return builder; + } + + public static RuntimeAppsAuthenticationBuilder AddCookieAuthenticationSessionIssuer(this RuntimeAppsAuthenticationBuilder builder, Action configure = null) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + EnsureNoSessionIssuer(builder.Services); + builder.Services.AddOptions(); + if(configure != null) builder.Services.Configure(configure); + builder.Services.AddScoped, RuntimeApps.Authentication.Features.Account.Services.CookieAuthenticationSessionIssuer>(); + return builder; + } + + private static void EnsureNoSessionIssuer(IServiceCollection services) where TUser : class { + if(services.Any(d => d.ServiceType == typeof(RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer))) + throw new InvalidOperationException("An authentication session issuer is already registered for this user type."); + } + private static void AddJwtProvider(RuntimeAppsAuthenticationBuilder builder, string scheme) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => builder.Services.TryAddScoped>(services => new JwtProvider( diff --git a/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs new file mode 100644 index 0000000..906722c --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs @@ -0,0 +1,8 @@ +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Features.Account.Contracts { + /// Establishes an authentication session for an account that has already passed eligibility checks. + public interface IAuthenticationSessionIssuer where TUser : class { + Task IssueAsync(TUser user, CancellationToken cancellationToken = default); + } +} diff --git a/RuntimeApps.Authentication/Features/Account/Models/CookieSessionOptions.cs b/RuntimeApps.Authentication/Features/Account/Models/CookieSessionOptions.cs new file mode 100644 index 0000000..0d1f7bf --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Models/CookieSessionOptions.cs @@ -0,0 +1,6 @@ +namespace RuntimeApps.Authentication.Features.Account.Models { + public sealed class CookieSessionOptions { + public bool IsPersistent { get; set; } + public string Scheme { get; set; } = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme; + } +} diff --git a/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs new file mode 100644 index 0000000..0113271 --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Features.Account.Services { + public sealed class CookieAuthenticationSessionIssuer : IAuthenticationSessionIssuer + where TUser : IdentityUser where TKey : IEquatable { + private readonly IUserClaimsPrincipalFactory _principalFactory; private readonly IHttpContextAccessor _http; + private readonly CookieSessionOptions _cookie; private readonly IRefreshTokenService _refresh; + private readonly RefreshTokenOptions _refreshOptions; + public CookieAuthenticationSessionIssuer(IUserClaimsPrincipalFactory principalFactory, IHttpContextAccessor http, + IOptions cookie, IRefreshTokenService refresh = null, IOptions refreshOptions = null) { + _principalFactory=principalFactory; _http=http; _cookie=cookie.Value; _refresh=refresh; _refreshOptions=refreshOptions?.Value ?? new(); + } + public async Task IssueAsync(TUser user, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + var context = _http.HttpContext ?? throw new InvalidOperationException("An HTTP context is required to issue a cookie session."); + var principal = await _principalFactory.CreateAsync(user); + await context.SignInAsync(_cookie.Scheme, principal, new AuthenticationProperties { IsPersistent = _cookie.IsPersistent }); + if(_refresh == null) return null; + var old=context.Request.Cookies[_refreshOptions.CookieName]; + if(!string.IsNullOrEmpty(old)) await _refresh.RevokeAsync(old, cancellationToken); + var session=await _refresh.CreateSessionAsync(user.Id, cancellationToken:cancellationToken); + context.Response.Cookies.Append(_refreshOptions.CookieName, session.RefreshToken, new CookieOptions { HttpOnly=true, Secure=_refreshOptions.CookieSecure, SameSite=_refreshOptions.CookieSameSite, Path=_refreshOptions.CookiePath, Expires=session.ExpiresAt }); + return null; + } + } +} diff --git a/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs new file mode 100644 index 0000000..e83b868 --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs @@ -0,0 +1,31 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Features.Account.Services { + public sealed class JwtAuthenticationSessionIssuer : IAuthenticationSessionIssuer + where TUser : IdentityUser where TKey : IEquatable { + private readonly IJwtProvider _jwtProvider; + private readonly IRefreshTokenService _refreshTokens; + private readonly IHttpContextAccessor _http; + private readonly RefreshTokenOptions _options; + public JwtAuthenticationSessionIssuer(IJwtProvider jwtProvider, IHttpContextAccessor http, + IRefreshTokenService refreshTokens = null, IOptions options = null) { + _jwtProvider = jwtProvider; _http = http; _refreshTokens = refreshTokens; _options = options?.Value ?? new(); + } + public async Task IssueAsync(TUser user, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + var token = await _jwtProvider.GenerateTokenAsync(user); + if(_refreshTokens != null) { + var session = await _refreshTokens.CreateSessionAsync(user.Id, cancellationToken: cancellationToken); + token.RefreshToken = session.RefreshToken; token.RefreshTokenExpireDate = session.ExpiresAt; token.SessionId = session.SessionId; + } + return token; + } + } +} diff --git a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs index 01b85c9..7466f17 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs @@ -4,10 +4,10 @@ using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Features.Account.Contracts; using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; -using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; using RuntimeApps.Authentication.Features.Verification.Contracts; -using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Identity.Contracts; using RuntimeApps.Authentication.Features.Verification.Models; using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Features.Account.Services { @@ -18,17 +18,12 @@ public class UserAccountService: IUserAccountService private readonly IUserLoginManager _loginManager; private readonly IUserEmailManager _emailManager; private readonly ISignInManager _signInManager; - private readonly IJwtProvider _jwtUtils; - private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; - private readonly IAuthenticationHandlerProvider _authenticationHandlerProvider; - private readonly IHttpContextAccessor _contextAccessor; - private readonly IUserClaimsPrincipalFactory _userClaimsPrincipalFactory; + private readonly Microsoft.AspNetCore.Http.IHttpContextAccessor _contextAccessor; private readonly IEnumerable> _externalLoginProviders; - private readonly IRefreshTokenService _refreshTokenService; - private readonly RefreshTokenOptions _refreshTokenOptions; private readonly IExternalLoginEmailTrustPolicy _externalLoginEmailTrustPolicy; private readonly VerificationOptions _verificationOptions; private readonly IVerificationWorkflowService _verificationWorkflow; + private readonly IAuthenticationSessionIssuer _sessionIssuer; // Preserve the original public constructor for existing compiled consumers. public UserAccountService(IUserManager userManager, @@ -58,22 +53,18 @@ public UserAccountService(IUserManager userManager, IOptions verificationOptions = null, IVerificationWorkflowService verificationWorkflow = null, IUserLoginManager loginManager = null, - IUserEmailManager emailManager = null) { + IUserEmailManager emailManager = null, + IAuthenticationSessionIssuer sessionIssuer = null) { _userManager = userManager; _loginManager = loginManager ?? userManager as IUserLoginManager; _emailManager = emailManager ?? userManager as IUserEmailManager; _signInManager = signInManager; - _jwtUtils = jwtUtils; _externalLoginProviders = externalLoginProviders; - _authenticationHandlerProvider = authenticationHandlerProvider; _contextAccessor = contextAccessor; - _userClaimsPrincipalFactory = userClaimsPrincipalFactory; - _authenticationSchemeProvider = authenticationSchemeProvider; - _refreshTokenService = refreshTokenService; - _refreshTokenOptions = refreshTokenOptions?.Value ?? new RefreshTokenOptions(); _externalLoginEmailTrustPolicy = externalLoginEmailTrustPolicy; _verificationOptions = verificationOptions?.Value ?? new VerificationOptions(); _verificationWorkflow = verificationWorkflow; + _sessionIssuer = sessionIssuer; } public virtual async Task> ExternalLoginAsync(string providerName, string token) { @@ -154,6 +145,16 @@ public virtual async Task> ExternalLoginAsync(string provid }); } + // A validated provider identity is only the first factor. Never issue a normal + // application session for an account that requires Identity two-factor auth. + if(user.TwoFactorEnabled) { + var challenge = await _signInManager.CreateTwoFactorChallengeAsync(user); + if(!challenge.RequiresTwoFactor) + return GetIdentityError(challenge); + return new Result(ResultCode.Accepted, + Result.CreateErrors("TwoFactorRequired", "Two factor authentication required")); + } + return await GenerateTokenAsync(user); } @@ -162,7 +163,7 @@ public virtual async Task> LoginAsync(string userName, stri if(userInfo == null || !userInfo.EmailConfirmed) return GetIdentityError(SignInResult.Failed); - var signInResult = await _signInManager.PasswordSignInAsync(userInfo, password, true, false); + var signInResult = await _signInManager.PasswordSignInAsync(userInfo, password, false, true); if(!signInResult.Succeeded) return GetIdentityError(signInResult); @@ -197,61 +198,11 @@ protected virtual Result GetIdentityError(SignInResult signInResul } protected virtual async Task> GenerateTokenAsync(TUser user) { - bool hasHandler = await HasHandlerAsync(); - - if(hasHandler) { - var claims = await _userClaimsPrincipalFactory.CreateAsync(user); - await _contextAccessor.HttpContext.SignInAsync(claims); - - if(_refreshTokenService != null) { - var httpContext = _contextAccessor.HttpContext; - var cancellationToken = httpContext?.RequestAborted ?? CancellationToken.None; - var existingRefreshToken = httpContext?.Request.Cookies[_refreshTokenOptions.CookieName]; - if(!string.IsNullOrEmpty(existingRefreshToken)) - await _refreshTokenService.RevokeAsync(existingRefreshToken, cancellationToken); - - var refreshSession = await _refreshTokenService.CreateSessionAsync( - user.Id, cancellationToken: cancellationToken); - AppendRefreshCookie(refreshSession.RefreshToken, refreshSession.ExpiresAt); - } - return new Result(user, null); - } - - var token = await _jwtUtils.GenerateTokenAsync(user); - if(_refreshTokenService != null) { - var cancellationToken = _contextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None; - var refreshSession = await _refreshTokenService.CreateSessionAsync( - user.Id, cancellationToken: cancellationToken); - token.RefreshToken = refreshSession.RefreshToken; - token.RefreshTokenExpireDate = refreshSession.ExpiresAt; - token.SessionId = refreshSession.SessionId; - } + if(_sessionIssuer == null) + throw new InvalidOperationException("An authentication session issuer must be explicitly registered."); + var token = await _sessionIssuer.IssueAsync(user, _contextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None); return new Result(user, token); } - private void AppendRefreshCookie(string refreshToken, DateTimeOffset expiresAt) { - var context = _contextAccessor.HttpContext; - if(context == null) - throw new InvalidOperationException("An HTTP context is required to issue a refresh-token cookie."); - - context.Response.Cookies.Append(_refreshTokenOptions.CookieName, refreshToken, new CookieOptions { - HttpOnly = true, - Secure = _refreshTokenOptions.CookieSecure, - SameSite = _refreshTokenOptions.CookieSameSite, - Path = _refreshTokenOptions.CookiePath, - Expires = expiresAt - }); - } - - private async Task HasHandlerAsync() { - var defaultScheme = await _authenticationSchemeProvider.GetDefaultSignInSchemeAsync(); - if(defaultScheme?.Name == null) - return false; - - var handler = await _authenticationHandlerProvider.GetHandlerAsync(_contextAccessor.HttpContext, defaultScheme.Name); - if(handler == null) - return false; - return handler is IAuthenticationSignInHandler; - } } } diff --git a/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs b/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs index 0b8835e..edf394a 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs @@ -25,6 +25,7 @@ public interface ISignInManager where TUser : class { Task TwoFactorAuthenticatorSignInAsync(string code, bool isPersistent, bool rememberClient); Task TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberClient); Task GetTwoFactorAuthenticationUserAsync(); + Task CreateTwoFactorChallengeAsync(TUser user); Task ExternalLoginSignInAsync(string loginProvider, string providerKey, bool isPersistent); Task ExternalLoginSignInAsync(string loginProvider, string providerKey, bool isPersistent, bool bypassTwoFactor); diff --git a/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs b/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs index d6e2293..ddba257 100644 --- a/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs +++ b/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs @@ -12,12 +12,15 @@ public RuntimeAppsSignInManager(UserManager userManager, IHttpContextAcce protected override async Task SignInOrTwoFactorAsync(TUser user, bool isPersistent, string loginProvider = null, bool bypassTwoFactor = false) { if(!bypassTwoFactor && await IsTfaEnabled(user)) { - return SignInResult.TwoFactorRequired; + return await base.SignInOrTwoFactorAsync(user, isPersistent, loginProvider, bypassTwoFactor); } return SignInResult.Success; } + public Task CreateTwoFactorChallengeAsync(TUser user) => + SignInOrTwoFactorAsync(user, false, "RuntimeApps.External", false); + protected virtual async Task IsTfaEnabled(TUser user) => UserManager.SupportsUserTwoFactor && await UserManager.GetTwoFactorEnabledAsync(user) && diff --git a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs index b8228fa..8f0b465 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs @@ -27,8 +27,8 @@ var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext(options => options.UseSqlServer(connectionString)); -builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddCookie(JwtBearerDefaults.AuthenticationScheme) +builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie() .AddRuntimeAppsAuthentication, IdentityRole, int>() .AddEfStores, IdentityRole, int>() .AddEfRefreshTokenStore, IdentityRole, int>() @@ -36,6 +36,7 @@ options.TokenLifetime = TimeSpan.FromDays(30); options.RevokeFamilyOnReuse = true; }) + .AddCookieAuthenticationSessionIssuer() .AddDefaultUserMapper>() .AddValidators(); From 40d7278c911abbc11f01277681b5268f01da4f2e Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 14:02:32 +0100 Subject: [PATCH 2/4] Add cancelation token for tasks --- ReadMe.md | 4 + .../FeatureRegistrationExtensions.cs | 12 +- ...ccountApiEndpointRouteBuilderExtensions.cs | 8 +- ...hTokenApiEndpointRouteBuilderExtensions.cs | 9 +- .../Account/Contracts/IUserAccountService.cs | 7 +- .../CookieAuthenticationSessionIssuer.cs | 24 ++- .../JwtAuthenticationSessionIssuer.cs | 13 +- .../Features/Account/Services/JwtProvider.cs | 4 +- .../Account/Services/UserAccountService.cs | 45 ++-- .../Contracts/IExternalLoginProvider.cs | 2 +- .../FacebookExternalLoginProvider.cs | 10 +- .../Providers/GoogleExternalLoginProvider.cs | 6 +- .../MicrosoftExternalLoginProvider.cs | 7 +- .../Services/RegistrationService.cs | 2 +- .../Identity/Contracts/IJwtProvider.cs | 3 +- .../Identity/Contracts/ISignInManager.cs | 2 - .../Identity/RuntimeAppsSignInManager.cs | 5 +- .../AuthenticationSessionIssuerTest.cs | 197 ++++++++++++++++++ .../UserAccountServiceTest.cs | 51 ++++- .../VerificationPrimitivesTest.cs | 4 +- 20 files changed, 336 insertions(+), 79 deletions(-) create mode 100644 Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs diff --git a/ReadMe.md b/ReadMe.md index 18337b1..1ce4a9e 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -111,8 +111,12 @@ Actions alone remain supported. Defaults are supplied by each options type; conf 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 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`, `IJwtProvider`, or `IExternalLoginProvider` directly should add the new optional cancellation-token parameter(s). 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: diff --git a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs index 18b0064..2da988e 100644 --- a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs +++ b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs @@ -105,7 +105,7 @@ public static RuntimeAppsAuthenticationBuilder UseJwt AddJwtAuthenticationSessionIssuer(this RuntimeAppsAuthenticationBuilder builder) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { ArgumentNullException.ThrowIfNull(builder); - EnsureNoSessionIssuer(builder.Services); + if(!RegisterSessionIssuer>(builder.Services)) return builder; builder.Services.AddScoped, RuntimeApps.Authentication.Features.Account.Services.JwtAuthenticationSessionIssuer>(); return builder; } @@ -113,16 +113,18 @@ public static RuntimeAppsAuthenticationBuilder AddJwtAuthent public static RuntimeAppsAuthenticationBuilder AddCookieAuthenticationSessionIssuer(this RuntimeAppsAuthenticationBuilder builder, Action configure = null) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { ArgumentNullException.ThrowIfNull(builder); - EnsureNoSessionIssuer(builder.Services); + if(!RegisterSessionIssuer>(builder.Services)) return builder; builder.Services.AddOptions(); if(configure != null) builder.Services.Configure(configure); builder.Services.AddScoped, RuntimeApps.Authentication.Features.Account.Services.CookieAuthenticationSessionIssuer>(); return builder; } - private static void EnsureNoSessionIssuer(IServiceCollection services) where TUser : class { - if(services.Any(d => d.ServiceType == typeof(RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer))) - throw new InvalidOperationException("An authentication session issuer is already registered for this user type."); + private static bool RegisterSessionIssuer(IServiceCollection services) where TUser : class { + var existing = services.LastOrDefault(d => d.ServiceType == typeof(RuntimeApps.Authentication.Features.Account.Contracts.IAuthenticationSessionIssuer)); + 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(RuntimeAppsAuthenticationBuilder builder, string scheme) diff --git a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs index bc867be..0fca15b 100644 --- a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs @@ -28,16 +28,16 @@ public static IEndpointRouteBuilder MapLoginApi(this IEnd IEnumerable> externalLoginProviders = endpoints.ServiceProvider.GetServices>(); - routeGroup.MapPost("login", async Task>, ValidationProblem>> ([FromBody] UserLoginModel userLoginModel, IUserAccountService userAccountService, [FromServices] IUserMapper mapper) => { - var result = await userAccountService.LoginAsync(userLoginModel.UserName, userLoginModel.Password); + routeGroup.MapPost("login", async Task>, ValidationProblem>> ([FromBody] UserLoginModel userLoginModel, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + var result = await userAccountService.LoginAsync(userLoginModel.UserName, userLoginModel.Password, context.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(MapResult(result, mapper)); }); if(externalLoginProviders?.Any() == true) { - routeGroup.MapPost("login/external", async Task>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService userAccountService, [FromServices] IUserMapper mapper) => { - var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token); + routeGroup.MapPost("login/external", async Task>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token, context.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(MapResult(result, mapper)); diff --git a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs index fd47b47..5ff955f 100644 --- a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -10,6 +10,7 @@ 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.Identity.Contracts; namespace RuntimeApps.Authentication.Endpoints.RefreshTokens { public static class RefreshTokenApiEndpointRouteBuilderExtensions { @@ -27,12 +28,14 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi IUserLockoutManager lockoutManager, IUserLoginManager loginManager, ISignInManager signInManager, + IUserClaimsPrincipalFactory principalFactory, IRefreshTokenService refreshTokenService, IRefreshTokenRequestLimiter requestLimiter, IServiceProvider services, IAuthenticationSchemeProvider schemeProvider, IAuthenticationHandlerProvider handlerProvider, IOptions options, + IOptions cookieOptions, IOptions verificationOptions) => { if(!await requestLimiter.IsAllowedAsync(context, context.RequestAborted)) return Results.StatusCode(StatusCodes.Status429TooManyRequests); @@ -70,7 +73,9 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(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(); } @@ -81,7 +86,7 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(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; diff --git a/RuntimeApps.Authentication/Features/Account/Contracts/IUserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Contracts/IUserAccountService.cs index b1ac03a..d017e84 100644 --- a/RuntimeApps.Authentication/Features/Account/Contracts/IUserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Contracts/IUserAccountService.cs @@ -1,8 +1,9 @@ using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Features.Account.Contracts { + /// ASP.NET Core Identity lookup and sign-in methods currently used by this service do not accept cancellation tokens. public interface IUserAccountService { - Task> CompleteRegistrationAsync(TUser user); - Task> LoginAsync(string userName, string password); - Task> ExternalLoginAsync(string provider, string token); + Task> CompleteRegistrationAsync(TUser user, CancellationToken cancellationToken = default); + Task> LoginAsync(string userName, string password, CancellationToken cancellationToken = default); + Task> ExternalLoginAsync(string provider, string token, CancellationToken cancellationToken = default); } } diff --git a/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs index 0113271..f2565e9 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs @@ -22,12 +22,26 @@ public async Task IssueAsync(TUser user, CancellationToken cancellationTo cancellationToken.ThrowIfCancellationRequested(); var context = _http.HttpContext ?? throw new InvalidOperationException("An HTTP context is required to issue a cookie session."); var principal = await _principalFactory.CreateAsync(user); + cancellationToken.ThrowIfCancellationRequested(); + RefreshTokenSession session = null; + if(_refresh != null) { + session = await _refresh.CreateSessionAsync(user.Id, cancellationToken:cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + if(session == null) + throw new InvalidOperationException("The refresh-token service did not create a session."); + var old = context.Request.Cookies[_refreshOptions.CookieName]; + try { + if(!string.IsNullOrEmpty(old)) await _refresh.RevokeAsync(old, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + await context.SignInAsync(_cookie.Scheme, principal, new AuthenticationProperties { IsPersistent = _cookie.IsPersistent }); + } catch { + await _refresh.RevokeAsync(session.RefreshToken, CancellationToken.None); + throw; + } + context.Response.Cookies.Append(_refreshOptions.CookieName, session.RefreshToken, new CookieOptions { HttpOnly=true, Secure=_refreshOptions.CookieSecure, SameSite=_refreshOptions.CookieSameSite, Path=_refreshOptions.CookiePath, Expires=session.ExpiresAt }); + return null; + } await context.SignInAsync(_cookie.Scheme, principal, new AuthenticationProperties { IsPersistent = _cookie.IsPersistent }); - if(_refresh == null) return null; - var old=context.Request.Cookies[_refreshOptions.CookieName]; - if(!string.IsNullOrEmpty(old)) await _refresh.RevokeAsync(old, cancellationToken); - var session=await _refresh.CreateSessionAsync(user.Id, cancellationToken:cancellationToken); - context.Response.Cookies.Append(_refreshOptions.CookieName, session.RefreshToken, new CookieOptions { HttpOnly=true, Secure=_refreshOptions.CookieSecure, SameSite=_refreshOptions.CookieSameSite, Path=_refreshOptions.CookiePath, Expires=session.ExpiresAt }); return null; } } diff --git a/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs index e83b868..d6cec01 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs @@ -1,9 +1,6 @@ using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Features.Account.Contracts; using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; -using RuntimeApps.Authentication.Features.RefreshTokens.Models; using RuntimeApps.Authentication.Identity.Contracts; using RuntimeApps.Authentication.Shared.Models; @@ -12,15 +9,13 @@ public sealed class JwtAuthenticationSessionIssuer : IAuthenticatio where TUser : IdentityUser where TKey : IEquatable { private readonly IJwtProvider _jwtProvider; private readonly IRefreshTokenService _refreshTokens; - private readonly IHttpContextAccessor _http; - private readonly RefreshTokenOptions _options; - public JwtAuthenticationSessionIssuer(IJwtProvider jwtProvider, IHttpContextAccessor http, - IRefreshTokenService refreshTokens = null, IOptions options = null) { - _jwtProvider = jwtProvider; _http = http; _refreshTokens = refreshTokens; _options = options?.Value ?? new(); + public JwtAuthenticationSessionIssuer(IJwtProvider jwtProvider, IRefreshTokenService refreshTokens = null) { + _jwtProvider = jwtProvider; _refreshTokens = refreshTokens; } public async Task IssueAsync(TUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var token = await _jwtProvider.GenerateTokenAsync(user); + var token = await _jwtProvider.GenerateTokenAsync(user, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); if(_refreshTokens != null) { var session = await _refreshTokens.CreateSessionAsync(user.Id, cancellationToken: cancellationToken); token.RefreshToken = session.RefreshToken; token.RefreshTokenExpireDate = session.ExpiresAt; token.SessionId = session.SessionId; diff --git a/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs b/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs index 746a7cf..f2b3671 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs @@ -20,10 +20,12 @@ public JwtProvider(JwtBearerOptions options, IUserClaimsPrincipalFactory _jwtOption = options ?? throw new ArgumentNullException(nameof(options)); _userClaimsPrincipalFactory = userClaimsPrincipalFactory ?? throw new ArgumentNullException(nameof(userClaimsPrincipalFactory)); } - public async Task GenerateTokenAsync(TUser user) { + public async Task GenerateTokenAsync(TUser user, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var credential = new SigningCredentials(_jwtOption.TokenValidationParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256); var claims = await _userClaimsPrincipalFactory.CreateAsync(user); + cancellationToken.ThrowIfCancellationRequested(); DateTime expire = DateTime.UtcNow.Add(_jwtOption.RefreshInterval); var token = new JwtSecurityToken(_jwtOption.TokenValidationParameters.ValidIssuer, _jwtOption.TokenValidationParameters.ValidAudience, diff --git a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs index 7466f17..3a434d6 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs @@ -67,22 +67,26 @@ public UserAccountService(IUserManager userManager, _sessionIssuer = sessionIssuer; } - public virtual async Task> ExternalLoginAsync(string providerName, string token) { - var provider = _externalLoginProviders.FirstOrDefault(p => p.Provider.Equals(providerName, StringComparison.OrdinalIgnoreCase)); + public virtual async Task> ExternalLoginAsync(string providerName, string token, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + var provider = _externalLoginProviders.FirstOrDefault(p => string.Equals(p.Provider, providerName, StringComparison.OrdinalIgnoreCase)); if(provider == null) return new Result(ResultCode.BadRequest, Result.CreateErrors("Unknown provider", "Provider is not added to system")); - var providerResult = await provider.ValidateAsync(token); + var providerResult = await provider.ValidateAsync(token, cancellationToken); if(providerResult?.LoginInfo == null || providerResult.User == null) return new Result(ResultCode.BadRequest, Result.CreateErrors("Invalid token", "Invalid External Authentication.")); var loginInfo = providerResult.LoginInfo; + // Identity manager/store APIs used below have no CancellationToken overloads. var user = await _loginManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); + cancellationToken.ThrowIfCancellationRequested(); if(user == null) { var trustedEmail = _externalLoginEmailTrustPolicy?.IsEmailTrusted(provider.Provider, providerResult) == true; var existingEmailUser = string.IsNullOrWhiteSpace(providerResult.Email) ? null : await _emailManager.FindByEmailAsync(providerResult.Email); + cancellationToken.ThrowIfCancellationRequested(); if(existingEmailUser != null) { // Never link an external identity to an existing account based on an unverified email. @@ -95,11 +99,13 @@ public virtual async Task> ExternalLoginAsync(string provid if(!user.EmailConfirmed) { user.EmailConfirmed = true; var updateResult = await _userManager.UpdateAsync(user); + cancellationToken.ThrowIfCancellationRequested(); if(!updateResult.Succeeded) return new Result(ResultCode.BadRequest, updateResult.Errors); } var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); + cancellationToken.ThrowIfCancellationRequested(); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); } else { @@ -113,10 +119,12 @@ public virtual async Task> ExternalLoginAsync(string provid user.EmailConfirmed = trustedEmail; var createResult = await _userManager.CreateAsync(user); + cancellationToken.ThrowIfCancellationRequested(); if(!createResult.Succeeded) return new Result(ResultCode.BadRequest, createResult.Errors); var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); + cancellationToken.ThrowIfCancellationRequested(); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); } @@ -132,7 +140,7 @@ public virtual async Task> ExternalLoginAsync(string provid Result.CreateErrors("EmailVerificationRequired", "Email verification is required but no verified email address or verification workflow is available.")); var verification = await _verificationWorkflow.StartAsync( - user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email); + user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, cancellationToken: cancellationToken); if(!verification.Succeeded) return new Result( ResultCode.Forbidden, @@ -145,38 +153,32 @@ public virtual async Task> ExternalLoginAsync(string provid }); } - // A validated provider identity is only the first factor. Never issue a normal - // application session for an account that requires Identity two-factor auth. - if(user.TwoFactorEnabled) { - var challenge = await _signInManager.CreateTwoFactorChallengeAsync(user); - if(!challenge.RequiresTwoFactor) - return GetIdentityError(challenge); - return new Result(ResultCode.Accepted, - Result.CreateErrors("TwoFactorRequired", "Two factor authentication required")); - } - - return await GenerateTokenAsync(user); + return await GenerateTokenAsync(user, cancellationToken); } - public virtual async Task> LoginAsync(string userName, string password) { + /// Identity lookup and password sign-in abstractions in ASP.NET Core do not expose cancellation overloads. + public virtual async Task> LoginAsync(string userName, string password, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var userInfo = await _userManager.FindByNameAsync(userName); + cancellationToken.ThrowIfCancellationRequested(); if(userInfo == null || !userInfo.EmailConfirmed) return GetIdentityError(SignInResult.Failed); var signInResult = await _signInManager.PasswordSignInAsync(userInfo, password, false, true); + cancellationToken.ThrowIfCancellationRequested(); if(!signInResult.Succeeded) return GetIdentityError(signInResult); - return await GenerateTokenAsync(userInfo); + return await GenerateTokenAsync(userInfo, cancellationToken); } - public virtual Task> CompleteRegistrationAsync(TUser user) { + public virtual Task> CompleteRegistrationAsync(TUser user, CancellationToken cancellationToken = default) { if(user == null || !user.EmailConfirmed) return Task.FromResult(new Result( ResultCode.Forbidden, Result.CreateErrors("EmailNotConfirmed", "The account must complete email verification before registration can be completed."))); - return GenerateTokenAsync(user); + return GenerateTokenAsync(user, cancellationToken); } protected virtual Result GetIdentityError(SignInResult signInResult) { @@ -197,10 +199,11 @@ protected virtual Result GetIdentityError(SignInResult signInResul return new Result(code, Result.CreateErrors(signInResult.ToString(), description)); } - protected virtual async Task> GenerateTokenAsync(TUser user) { + protected virtual async Task> GenerateTokenAsync(TUser user, CancellationToken cancellationToken = default) { if(_sessionIssuer == null) throw new InvalidOperationException("An authentication session issuer must be explicitly registered."); - var token = await _sessionIssuer.IssueAsync(user, _contextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None); + cancellationToken.ThrowIfCancellationRequested(); + var token = await _sessionIssuer.IssueAsync(user, cancellationToken); return new Result(user, token); } diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginProvider.cs index cf75d97..13978a6 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginProvider.cs @@ -2,6 +2,6 @@ namespace RuntimeApps.Authentication.Features.ExternalLogin.Contracts { public interface IExternalLoginProvider where TUser : class { string Provider { get; } - Task> ValidateAsync(string token); + Task> ValidateAsync(string token, CancellationToken cancellationToken = default); } } diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs index ea62bde..25e4fcc 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs @@ -27,7 +27,7 @@ public FacebookExternalLoginProvider( public string Provider => "FACEBOOK"; - public async Task> ValidateAsync(string token) { + public async Task> ValidateAsync(string token, CancellationToken cancellationToken = default) { var option = _options.Value; if(string.IsNullOrWhiteSpace(token) || !long.TryParse(option.ClientId, NumberStyles.None, CultureInfo.InvariantCulture, out var configuredAppId)) @@ -41,14 +41,14 @@ public async Task> ValidateAsync(string token using var client = _httpClientFactory.CreateClient(nameof(FacebookExternalLoginProvider)); var appTokenUrl = string.Format(CultureInfo.InvariantCulture, option.AccessTokenUrl, Uri.EscapeDataString(option.ClientId), Uri.EscapeDataString(option.ClientSecret)); - var appTokenResponse = await client.GetStringAsync(appTokenUrl); + var appTokenResponse = await client.GetStringAsync(appTokenUrl, cancellationToken); var appToken = JsonConvert.DeserializeObject(appTokenResponse); if(string.IsNullOrWhiteSpace(appToken?.Access_token)) return null; var debugUrl = string.Format(CultureInfo.InvariantCulture, option.DebugTokenUrl, Uri.EscapeDataString(token), Uri.EscapeDataString(appToken.Access_token)); - var debugResponse = await client.GetStringAsync(debugUrl); + var debugResponse = await client.GetStringAsync(debugUrl, cancellationToken); var debugData = JsonConvert.DeserializeObject(debugResponse)?.Data; if(debugData == null || !debugData.Is_valid || debugData.App_id != configuredAppId || debugData.User_Id == null || @@ -56,7 +56,7 @@ public async Task> ValidateAsync(string token return null; var userUrl = $"https://graph.facebook.com/{graphApiVersion}/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={Uri.EscapeDataString(token)}"; - var userResponse = await client.GetStringAsync(userUrl); + var userResponse = await client.GetStringAsync(userUrl, cancellationToken); var userInfo = JsonConvert.DeserializeObject(userResponse); if(userInfo?.Id == null || userInfo.Id.Value != debugData.User_Id.Value) return null; @@ -73,6 +73,8 @@ public async Task> ValidateAsync(string token // Facebook's current response model does not provide a trustworthy email-verified assertion. EmailVerified = false }; + } catch(OperationCanceledException) { + throw; } catch(HttpRequestException exception) { // Do not log request URLs: Facebook access tokens are sent in query parameters. _logger.LogWarning( diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs index 801e252..e5bd94d 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs @@ -19,7 +19,9 @@ public GoogleExternalLoginProvider( public string Provider => "GOOGLE"; - public async Task> ValidateAsync(string token) { + /// The Google token validation library does not expose cancellation. Cancellation is checked before validation begins. + public async Task> ValidateAsync(string token, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var option = _options.Value; if(string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(option.ClientId)) return null; @@ -44,6 +46,8 @@ public async Task> ValidateAsync(string token EmailVerified = payload.EmailVerified, HostedDomain = payload.HostedDomain }; + } catch(OperationCanceledException) { + throw; } catch(Exception exception) { // Log the validation reason, but never log the supplied identity token. _logger.LogWarning( diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs index f0ba232..b9e3702 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs @@ -25,7 +25,8 @@ public MicrosoftExternalLoginProvider( public string Provider => "MICROSOFT"; - public async Task> ValidateAsync(string token) { + public async Task> ValidateAsync(string token, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var option = _options.Value; if(string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(option.ClientId) || string.IsNullOrWhiteSpace(option.IssuerEndpoint) || string.IsNullOrWhiteSpace(option.ConfigurationAddress)) @@ -40,7 +41,7 @@ public async Task> ValidateAsync(string token using var client = _httpClientFactory.CreateClient(nameof(MicrosoftExternalLoginProvider)); var documentRetriever = new HttpDocumentRetriever(client) { RequireHttps = true }; var configuration = await OpenIdConnectConfigurationRetriever.GetAsync( - metadataAddress, documentRetriever, CancellationToken.None); + metadataAddress, documentRetriever, cancellationToken); var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(token, new TokenValidationParameters { @@ -83,6 +84,8 @@ public async Task> ValidateAsync(string token // Microsoft email claims are mutable and do not prove mailbox ownership. EmailVerified = false }; + } catch(OperationCanceledException) { + throw; } catch(SecurityTokenException exception) { _logger.LogWarning( "Microsoft identity token validation failed. {ExceptionType}: {Reason}", diff --git a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs index c977657..050ea07 100644 --- a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs +++ b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs @@ -89,7 +89,7 @@ public async Task> VerifyAsync( if(!verificationResult.Succeeded) return new Result(verificationResult.Code, verificationResult.Errors); - return await _accountService.CompleteRegistrationAsync(verificationResult.Data); + return await _accountService.CompleteRegistrationAsync(verificationResult.Data, cancellationToken); } public async Task> ResendAsync( diff --git a/RuntimeApps.Authentication/Identity/Contracts/IJwtProvider.cs b/RuntimeApps.Authentication/Identity/Contracts/IJwtProvider.cs index bff5067..8add2b3 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IJwtProvider.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IJwtProvider.cs @@ -2,6 +2,7 @@ namespace RuntimeApps.Authentication.Identity.Contracts { public interface IJwtProvider where TUser : class { - Task GenerateTokenAsync(TUser user); + /// Generates a JWT. Cancellation is observed around claim creation; Identity's principal factory has no cancellation overload. + Task GenerateTokenAsync(TUser user, CancellationToken cancellationToken = default); } } diff --git a/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs b/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs index edf394a..12594a8 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/ISignInManager.cs @@ -21,11 +21,9 @@ public interface ISignInManager where TUser : class { Task IsTwoFactorClientRememberedAsync(TUser user); Task RememberTwoFactorClientAsync(TUser user); Task ForgetTwoFactorClientAsync(); - Task TwoFactorRecoveryCodeSignInAsync(string recoveryCode); Task TwoFactorAuthenticatorSignInAsync(string code, bool isPersistent, bool rememberClient); Task TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberClient); Task GetTwoFactorAuthenticationUserAsync(); - Task CreateTwoFactorChallengeAsync(TUser user); Task ExternalLoginSignInAsync(string loginProvider, string providerKey, bool isPersistent); Task ExternalLoginSignInAsync(string loginProvider, string providerKey, bool isPersistent, bool bypassTwoFactor); diff --git a/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs b/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs index ddba257..d6e2293 100644 --- a/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs +++ b/RuntimeApps.Authentication/Identity/RuntimeAppsSignInManager.cs @@ -12,15 +12,12 @@ public RuntimeAppsSignInManager(UserManager userManager, IHttpContextAcce protected override async Task SignInOrTwoFactorAsync(TUser user, bool isPersistent, string loginProvider = null, bool bypassTwoFactor = false) { if(!bypassTwoFactor && await IsTfaEnabled(user)) { - return await base.SignInOrTwoFactorAsync(user, isPersistent, loginProvider, bypassTwoFactor); + return SignInResult.TwoFactorRequired; } return SignInResult.Success; } - public Task CreateTwoFactorChallengeAsync(TUser user) => - SignInOrTwoFactorAsync(user, false, "RuntimeApps.External", false); - protected virtual async Task IsTfaEnabled(TUser user) => UserManager.SupportsUserTwoFactor && await UserManager.GetTwoFactorEnabledAsync(user) && diff --git a/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs new file mode 100644 index 0000000..7ce8a87 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs @@ -0,0 +1,197 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Moq; +using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; +using RuntimeApps.Authentication.Features.Account.Services; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Test; + +public class AuthenticationSessionIssuerTest { + [Fact] + public async Task JwtIssuer_GeneratesTokenAndAddsRefreshSession() { + var user = new IdentityUser { Id = "u1" }; + var expected = new Token { AuthenticationToken = "access" }; + var jwt = new Mock>(); + jwt.Setup(p => p.GenerateTokenAsync(user, It.IsAny())).ReturnsAsync(expected); + var refresh = new Mock>(); + refresh.Setup(s => s.CreateSessionAsync("u1", null, It.IsAny())) + .ReturnsAsync(new RefreshTokenSession { UserId = "u1", SessionId = Guid.NewGuid(), RefreshToken = "refresh", ExpiresAt = DateTimeOffset.UtcNow.AddDays(1) }); + var issuer = new JwtAuthenticationSessionIssuer(jwt.Object, refresh.Object); + + var result = await issuer.IssueAsync(user); + + Assert.Same(expected, result); + Assert.Equal("refresh", result.RefreshToken); + Assert.NotNull(result.SessionId); + } + + [Fact] + public async Task JwtIssuer_PropagatesCancellationAndDoesNotIssue() { + var jwt = new Mock>(); + var issuer = new JwtAuthenticationSessionIssuer(jwt.Object); + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => issuer.IssueAsync(new IdentityUser(), cancellation.Token)); + jwt.Verify(p => p.GenerateTokenAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task JwtIssuer_PropagatesCancellationToProviderAndRefreshService() { + using var cancellation = new CancellationTokenSource(); + var user = new IdentityUser { Id = "u1" }; + var jwt = new Mock>(); + jwt.Setup(p => p.GenerateTokenAsync(user, cancellation.Token)).ReturnsAsync(new Token()); + var refresh = new Mock>(); + refresh.Setup(s => s.CreateSessionAsync("u1", null, cancellation.Token)) + .ReturnsAsync(new RefreshTokenSession { UserId = "u1", RefreshToken = "r", ExpiresAt = DateTimeOffset.UtcNow.AddDays(1) }); + var issuer = new JwtAuthenticationSessionIssuer(jwt.Object, refresh.Object); + + await issuer.IssueAsync(user, cancellation.Token); + + jwt.Verify(p => p.GenerateTokenAsync(user, cancellation.Token), Times.Once); + refresh.Verify(s => s.CreateSessionAsync("u1", null, cancellation.Token), Times.Once); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CookieIssuer_UsesExplicitPersistence(bool persistent) { + var user = new IdentityUser(); + var principal = new ClaimsPrincipal(new ClaimsIdentity("test")); + var principalFactory = new Mock>(); + principalFactory.Setup(f => f.CreateAsync(user)).ReturnsAsync(principal); + var auth = new Mock(); + auth.Setup(a => a.SignInAsync(It.IsAny(), "app-cookie", principal, It.IsAny())).Returns(Task.CompletedTask); + var services = new ServiceCollection().AddSingleton(auth.Object).BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = services }; + var accessor = new HttpContextAccessor { HttpContext = context }; + var cookieOptions = persistent + ? new CookieSessionOptions { IsPersistent = true, Scheme = "app-cookie" } + : new CookieSessionOptions { Scheme = "app-cookie" }; + var issuer = new CookieAuthenticationSessionIssuer(principalFactory.Object, accessor, + Options.Create(cookieOptions)); + + await issuer.IssueAsync(user); + + auth.Verify(a => a.SignInAsync(context, "app-cookie", principal, + It.Is(properties => properties.IsPersistent == persistent)), Times.Once); + } + + [Fact] + public async Task CookieIssuer_CreatesRefreshSessionBeforeEstablishingCookie() { + var user = new IdentityUser { Id = "u1" }; + var principalFactory = new Mock>(); + principalFactory.Setup(f => f.CreateAsync(user)).ReturnsAsync(new ClaimsPrincipal(new ClaimsIdentity("test"))); + var refresh = new Mock>(); + refresh.Setup(s => s.CreateSessionAsync("u1", null, It.IsAny())) + .ReturnsAsync(new RefreshTokenSession { UserId = "u1", RefreshToken = "refresh", ExpiresAt = DateTimeOffset.UtcNow.AddDays(1) }); + var auth = new Mock(); + auth.Setup(a => a.SignInAsync(It.IsAny(), "app-cookie", It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + var services = new ServiceCollection().AddSingleton(auth.Object).BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = services }; + var issuer = new CookieAuthenticationSessionIssuer(principalFactory.Object, + new HttpContextAccessor { HttpContext = context }, Options.Create(new CookieSessionOptions { Scheme = "app-cookie" }), refresh.Object); + + await issuer.IssueAsync(user); + + auth.Verify(a => a.SignInAsync(context, "app-cookie", It.IsAny(), It.IsAny()), Times.Once); + Assert.Contains("__Host-runtimeapps-refresh=refresh", context.Response.Headers.SetCookie.ToString()); + } + + [Fact] + public async Task CookieIssuer_RefreshCreationFailureDoesNotEstablishCookie() { + var user = new IdentityUser { Id = "u1" }; + var factory = new Mock>(); + factory.Setup(f => f.CreateAsync(user)).ReturnsAsync(new ClaimsPrincipal(new ClaimsIdentity("test"))); + var refresh = new Mock>(); + refresh.Setup(s => s.CreateSessionAsync("u1", null, It.IsAny())).ThrowsAsync(new InvalidOperationException("store failure")); + var auth = new Mock(); + var services = new ServiceCollection().AddSingleton(auth.Object).BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = services }; + var issuer = new CookieAuthenticationSessionIssuer(factory.Object, + new HttpContextAccessor { HttpContext = context }, Options.Create(new CookieSessionOptions { Scheme = "app-cookie" }), refresh.Object); + + await Assert.ThrowsAsync(() => issuer.IssueAsync(user)); + auth.Verify(a => a.SignInAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task CookieIssuer_SignInFailureRevokesNewRefreshCredential() { + var user = new IdentityUser { Id = "u1" }; + var factory = new Mock>(); + factory.Setup(f => f.CreateAsync(user)).ReturnsAsync(new ClaimsPrincipal(new ClaimsIdentity("test"))); + var refresh = new Mock>(); + refresh.Setup(s => s.CreateSessionAsync("u1", null, It.IsAny())) + .ReturnsAsync(new RefreshTokenSession { UserId = "u1", RefreshToken = "new-refresh", ExpiresAt = DateTimeOffset.UtcNow.AddDays(1) }); + refresh.Setup(s => s.RevokeAsync("new-refresh", CancellationToken.None)).ReturnsAsync(true); + var auth = new Mock(); + auth.Setup(a => a.SignInAsync(It.IsAny(), "app-cookie", It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("cookie failure")); + var services = new ServiceCollection().AddSingleton(auth.Object).BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = services }; + var issuer = new CookieAuthenticationSessionIssuer(factory.Object, + new HttpContextAccessor { HttpContext = context }, Options.Create(new CookieSessionOptions { Scheme = "app-cookie" }), refresh.Object); + + await Assert.ThrowsAsync(() => issuer.IssueAsync(user)); + refresh.Verify(s => s.RevokeAsync("new-refresh", CancellationToken.None), Times.Once); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); + } + + [Fact] + public void CookieSessionPersistence_DefaultsToFalse() => Assert.False(new CookieSessionOptions().IsPersistent); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CookieIssuer_ProducesSessionOrPersistentCookie(bool persistent) { + var options = new CookieSessionOptions { Scheme = "app-cookie", IsPersistent = persistent }; + var principalFactory = new Mock>(); + principalFactory.Setup(factory => factory.CreateAsync(It.IsAny())) + .ReturnsAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "user") }, "test"))); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDataProtection().UseEphemeralDataProtectionProvider(); + services.AddAuthentication(options.Scheme).AddCookie(options.Scheme); + using var serviceProvider = services.BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = serviceProvider }; + var issuer = new CookieAuthenticationSessionIssuer(principalFactory.Object, + new HttpContextAccessor { HttpContext = context }, Options.Create(options)); + + await issuer.IssueAsync(new IdentityUser()); + + var setCookie = Assert.Single(context.Response.Headers.SetCookie.ToArray()); + Assert.Equal(persistent, setCookie.Contains("expires=", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void IssuerRegistration_IsExplicitAndRejectsConflict() { + var services = new ServiceCollection(); + var builder = services.AddAuthentication().AddRuntimeAppsAuthentication(); + Assert.False(services.Any(d => d.ServiceType == typeof(IAuthenticationSessionIssuer))); + builder.AddCookieAuthenticationSessionIssuer(); + Assert.Single(services.Where(d => d.ServiceType == typeof(IAuthenticationSessionIssuer))); + Assert.Throws(() => builder.AddJwtAuthenticationSessionIssuer()); + } + + [Fact] + public void JwtUse_ExplicitlyRegistersJwtIssuer() { + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .UseJwt("jwt", options => { }); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IAuthenticationSessionIssuer) && + descriptor.ImplementationType == typeof(JwtAuthenticationSessionIssuer)); + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index 5326dfe..363afea 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -25,7 +25,7 @@ public class UserAccountServiceTest { private readonly Mock> _loginManagerMock; private readonly Mock> _emailManagerMock; private readonly Mock> _signInManagerMock; - private readonly Mock> _jwtProviderMock; + private readonly Mock> _sessionIssuerMock; private readonly Mock> _externalLoginProvider1; private readonly Mock> _externalLoginProvider2; private readonly Mock> _externalLoginEmailTrustPolicyMock; @@ -40,7 +40,7 @@ public UserAccountServiceTest() { _loginManagerMock = new Mock>(); _emailManagerMock = new Mock>(); _signInManagerMock = new Mock>(); - _jwtProviderMock = new Mock>(); + _sessionIssuerMock = new Mock>(); _externalLoginProvider1 = new Mock>(); _externalLoginProvider2 = new Mock>(); _externalLoginEmailTrustPolicyMock = new Mock>(); @@ -56,7 +56,7 @@ public UserAccountServiceTest() { _httpContextAccessorMock.Object, _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, - _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object, null, null, _loginManagerMock.Object, _emailManagerMock.Object); + null, null, null, _externalLoginEmailTrustPolicyMock.Object, null, null, _loginManagerMock.Object, _emailManagerMock.Object, _sessionIssuerMock.Object); _authenticationSchemeProviderMock.Setup(p => p.GetDefaultSignInSchemeAsync()) .ReturnsAsync((AuthenticationScheme)null); @@ -79,7 +79,7 @@ public async Task Login_Success() { .ReturnsAsync(user); _signInManagerMock.Setup(S => S.PasswordSignInAsync(user, password, It.IsAny(), It.IsAny())) .ReturnsAsync(SignInResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) + _sessionIssuerMock.Setup(t => t.IssueAsync(user, It.IsAny())) .ReturnsAsync(token); //Act @@ -144,6 +144,22 @@ public async Task Login_WrongPassword() { result.Meta.Should().BeNull(); } + [Theory] + [InlineData(true, RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict)] + [InlineData(false, RuntimeApps.Authentication.Shared.Models.ResultCode.Forbidden)] + public async Task Login_LockedOutOrNotAllowed_DoesNotIssueSession(bool lockedOut, RuntimeApps.Authentication.Shared.Models.ResultCode expectedCode) { + var user = new IdentityUser { UserName = "restricted", EmailConfirmed = true }; + _userManagerMock.Setup(manager => manager.FindByNameAsync(user.UserName)).ReturnsAsync(user); + _signInManagerMock.Setup(manager => manager.PasswordSignInAsync(user, "password", false, true)) + .ReturnsAsync(lockedOut ? SignInResult.LockedOut : SignInResult.NotAllowed); + + var result = await _userAccountService.LoginAsync(user.UserName, "password"); + + Assert.False(result.Succeeded); + Assert.Equal(expectedCode, result.Code); + _sessionIssuerMock.Verify(issuer => issuer.IssueAsync(It.IsAny(), It.IsAny()), Times.Never); + } + [Fact] public async Task CompleteRegistration_Success_ConfirmedUser() { var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = true }; @@ -151,7 +167,7 @@ public async Task CompleteRegistration_Success_ConfirmedUser() { AuthenticationToken = "", ExpireDate = DateTimeOffset.Now.AddDays(30), }; - _jwtProviderMock.Setup(provider => provider.GenerateTokenAsync(user)).ReturnsAsync(token); + _sessionIssuerMock.Setup(provider => provider.IssueAsync(user, It.IsAny())).ReturnsAsync(token); var result = await _userAccountService.CompleteRegistrationAsync(user); @@ -168,7 +184,20 @@ public async Task CompleteRegistration_UnconfirmedUser_IsRejected() { result.Succeeded.Should().BeFalse(); result.Code.Should().Be(RuntimeApps.Authentication.Shared.Models.ResultCode.Forbidden); - _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); + _sessionIssuerMock.Verify(provider => provider.IssueAsync(It.IsAny(), It.IsAny()), Times.Never()); + } + + [Fact] + public async Task CompleteRegistration_WithoutIssuer_FailsExplicitly() { + var service = new UserAccountService( + _userManagerMock.Object, _signInManagerMock.Object, Array.Empty>(), + _authenticationHandlerProviderMock.Object, _httpContextAccessorMock.Object, + _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, + null, null, null, _externalLoginEmailTrustPolicyMock.Object, null, null, + _loginManagerMock.Object, _emailManagerMock.Object, null); + + await Assert.ThrowsAsync(() => + service.CompleteRegistrationAsync(new IdentityUser { EmailConfirmed = true })); } [Fact] @@ -199,7 +228,7 @@ public async Task ExternalLogin_Success_CreateNewUser() { .ReturnsAsync(IdentityResult.Success); _loginManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) + _sessionIssuerMock.Setup(t => t.IssueAsync(user, It.IsAny())) .ReturnsAsync(appToken); //Act @@ -293,10 +322,10 @@ public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() new IExternalLoginProvider[] { _externalLoginProvider1.Object, _externalLoginProvider2.Object }, _authenticationHandlerProviderMock.Object, _httpContextAccessorMock.Object, _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, - _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object, + null, null, null, _externalLoginEmailTrustPolicyMock.Object, Microsoft.Extensions.Options.Options.Create(new RuntimeApps.Authentication.Features.Verification.Models.VerificationOptions { RequireEmailVerificationForExternalLogins = true - }), workflow.Object, _loginManagerMock.Object, _emailManagerMock.Object); + }), workflow.Object, _loginManagerMock.Object, _emailManagerMock.Object, _sessionIssuerMock.Object); var result = await service.ExternalLoginAsync(provider, token); @@ -304,7 +333,7 @@ public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() Assert.True(result.Meta.VerificationRequired); Assert.Equal("external-handle", result.Meta.VerificationHandle); Assert.Null(result.Meta.AuthenticationToken); - _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); + _sessionIssuerMock.Verify(provider => provider.IssueAsync(It.IsAny(), It.IsAny()), Times.Never()); } [Fact] @@ -331,7 +360,7 @@ public async Task ExternalLogin_Success_ExistsLogin() { .ReturnsAsync(user); _loginManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) + _sessionIssuerMock.Setup(t => t.IssueAsync(user, It.IsAny())) .ReturnsAsync(appToken); //Act diff --git a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs index 82e18a7..52ae92b 100644 --- a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs @@ -49,7 +49,7 @@ public async Task RandomVerificationCodeGenerator_GeneratesConfiguredNumericCode [Fact] public void DataProtectionVerifier_BindsCodeToRequestAndDestination() { var services = new ServiceCollection(); - services.AddDataProtection(); + services.AddDataProtection().UseEphemeralDataProtectionProvider(); using var provider = services.BuildServiceProvider(); var verifier = new DataProtectionVerificationCodeVerifier( provider.GetRequiredService()); @@ -76,4 +76,4 @@ public void VerificationOptions_RejectsInvalidSecurityLimits() { Assert.Throws(() => options.Validate()); } } -} \ No newline at end of file +} From 91c3fd5f4ddba0424700e3882ee9cd81c50551c1 Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 14:54:43 +0100 Subject: [PATCH 3/4] Fix review comments --- ReadMe.md | 4 +- ...hTokenApiEndpointRouteBuilderExtensions.cs | 71 ++++++++++--------- .../Contracts/IAuthenticationSessionIssuer.cs | 8 +++ .../CookieAuthenticationSessionIssuer.cs | 1 + .../JwtAuthenticationSessionIssuer.cs | 1 + .../AuthenticationSessionIssuerTest.cs | 30 ++++++++ 6 files changed, 78 insertions(+), 37 deletions(-) diff --git a/ReadMe.md b/ReadMe.md index 1ce4a9e..c3c6a7f 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -109,13 +109,13 @@ 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 tokens remain opt-in through `.AddRefreshToken(...)`: JWT clients receive refresh token data in the response, while cookie clients receive an HttpOnly refresh-token cookie. +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`, `IJwtProvider`, or `IExternalLoginProvider` directly should add the new optional cancellation-token parameter(s). Existing call sites can omit cancellation tokens; ASP.NET Core Identity calls that do not accept tokens remain non-cancellable once started. +Applications implementing `IUserAccountService`, `IJwtProvider`, or `IExternalLoginProvider` directly should add the new optional cancellation-token parameter(s). Applications supplying a custom `IAuthenticationSessionIssuer` 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. diff --git a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs index 5ff955f..b78501c 100644 --- a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -11,6 +11,7 @@ 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 { @@ -21,6 +22,10 @@ public static class RefreshTokenApiEndpointRouteBuilderExtensions { public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpointRouteBuilder endpoints) where TUser : IdentityUser where TKey : IEquatable { + if(endpoints.ServiceProvider.GetRequiredService() + .IsService(typeof(IAuthenticationSessionIssuer)) != true) + throw new InvalidOperationException("Refresh-token endpoints require exactly one explicitly registered authentication session issuer."); + var routes = endpoints.MapGroup(""); routes.MapPost("refresh", async Task (HttpContext context, @@ -32,15 +37,15 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi IRefreshTokenService refreshTokenService, IRefreshTokenRequestLimiter requestLimiter, IServiceProvider services, - IAuthenticationSchemeProvider schemeProvider, - IAuthenticationHandlerProvider handlerProvider, + IEnumerable> sessionIssuers, IOptions options, IOptions cookieOptions, IOptions 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(context.RequestAborted); @@ -102,10 +107,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, routes.MapPost("logout", async Task (HttpContext context, IRefreshTokenService refreshTokenService, - IOptions options) => { - var isCookie = await HasCookieSignInHandlerAsync(context, - context.RequestServices.GetRequiredService(), - context.RequestServices.GetRequiredService()); + IOptions options, + IOptions cookieOptions, + IEnumerable> sessionIssuers) => { + var isCookie = GetSessionMode(sessionIssuers) == AuthenticationSessionMode.Cookie; RefreshTokenRequest request = null; if(!isCookie && context.Request.HasJsonContentType()) request = await context.Request.ReadFromJsonAsync(context.RequestAborted); @@ -117,13 +122,9 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, : 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(true, "application/json") @@ -133,44 +134,44 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, routes.MapPost("logout/all", async Task (HttpContext context, IUserManager userManager, IRefreshTokenService refreshTokenService, - IOptions options) => { + IOptions options, + IOptions cookieOptions, + IEnumerable> 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(), - context.RequestServices.GetRequiredService()); 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 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(IEnumerable> 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) || diff --git a/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs index 906722c..4b7feb4 100644 --- a/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs +++ b/RuntimeApps.Authentication/Features/Account/Contracts/IAuthenticationSessionIssuer.cs @@ -1,8 +1,16 @@ using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Features.Account.Contracts { + public enum AuthenticationSessionMode { + Unspecified = 0, + Jwt = 1, + Cookie = 2 + } + /// Establishes an authentication session for an account that has already passed eligibility checks. public interface IAuthenticationSessionIssuer where TUser : class { + /// Identifies the explicitly registered mechanism used by refresh and logout operations. + AuthenticationSessionMode Mode => AuthenticationSessionMode.Unspecified; Task IssueAsync(TUser user, CancellationToken cancellationToken = default); } } diff --git a/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs index f2565e9..210ab7f 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/CookieAuthenticationSessionIssuer.cs @@ -14,6 +14,7 @@ public sealed class CookieAuthenticationSessionIssuer : IAuthentica private readonly IUserClaimsPrincipalFactory _principalFactory; private readonly IHttpContextAccessor _http; private readonly CookieSessionOptions _cookie; private readonly IRefreshTokenService _refresh; private readonly RefreshTokenOptions _refreshOptions; + public AuthenticationSessionMode Mode => AuthenticationSessionMode.Cookie; public CookieAuthenticationSessionIssuer(IUserClaimsPrincipalFactory principalFactory, IHttpContextAccessor http, IOptions cookie, IRefreshTokenService refresh = null, IOptions refreshOptions = null) { _principalFactory=principalFactory; _http=http; _cookie=cookie.Value; _refresh=refresh; _refreshOptions=refreshOptions?.Value ?? new(); diff --git a/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs index d6cec01..8cac627 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/JwtAuthenticationSessionIssuer.cs @@ -9,6 +9,7 @@ public sealed class JwtAuthenticationSessionIssuer : IAuthenticatio where TUser : IdentityUser where TKey : IEquatable { private readonly IJwtProvider _jwtProvider; private readonly IRefreshTokenService _refreshTokens; + public AuthenticationSessionMode Mode => AuthenticationSessionMode.Jwt; public JwtAuthenticationSessionIssuer(IJwtProvider jwtProvider, IRefreshTokenService refreshTokens = null) { _jwtProvider = jwtProvider; _refreshTokens = refreshTokens; } diff --git a/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs index 7ce8a87..c1e2a97 100644 --- a/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs @@ -3,12 +3,14 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Endpoints.RefreshTokens; using RuntimeApps.Authentication.Features.Account.Contracts; using RuntimeApps.Authentication.Features.Account.Models; using RuntimeApps.Authentication.Features.Account.Services; @@ -183,6 +185,8 @@ public void IssuerRegistration_IsExplicitAndRejectsConflict() { Assert.False(services.Any(d => d.ServiceType == typeof(IAuthenticationSessionIssuer))); builder.AddCookieAuthenticationSessionIssuer(); Assert.Single(services.Where(d => d.ServiceType == typeof(IAuthenticationSessionIssuer))); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IAuthenticationSessionIssuer) && + descriptor.ImplementationType == typeof(CookieAuthenticationSessionIssuer)); Assert.Throws(() => builder.AddJwtAuthenticationSessionIssuer()); } @@ -194,4 +198,30 @@ public void JwtUse_ExplicitlyRegistersJwtIssuer() { Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IAuthenticationSessionIssuer) && descriptor.ImplementationType == typeof(JwtAuthenticationSessionIssuer)); } + + [Fact] + public void SessionIssuerMode_IsExplicitAndIndependentOfDefaultSignInScheme() { + var services = new ServiceCollection(); + services.AddAuthentication(options => options.DefaultSignInScheme = "some-other-scheme"); + var jwtIssuer = new JwtAuthenticationSessionIssuer(new Mock>().Object); + var cookieIssuer = new CookieAuthenticationSessionIssuer( + new Mock>().Object, + new HttpContextAccessor(), Options.Create(new CookieSessionOptions { Scheme = "app-cookie" })); + + Assert.Equal(AuthenticationSessionMode.Jwt, jwtIssuer.Mode); + Assert.Equal(AuthenticationSessionMode.Cookie, cookieIssuer.Mode); + Assert.Equal("some-other-scheme", services.BuildServiceProvider() + .GetRequiredService>().Value.DefaultSignInScheme); + } + + [Fact] + public void RefreshEndpoints_RequireExplicitIssuerRegistration() { + var builder = WebApplication.CreateBuilder(); + using var app = builder.Build(); + + var error = Assert.Throws(() => app.MapRefreshTokenApi()); + + Assert.Contains("exactly one explicitly registered authentication session issuer", error.Message); + } + } From da4d8b6cb0173856f514e74d42767d8e1833b6a2 Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 15:04:47 +0100 Subject: [PATCH 4/4] Apply tests --- .../RefreshTokenEndpointModeTest.cs | 254 ++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs diff --git a/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs b/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs new file mode 100644 index 0000000..cd25804 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs @@ -0,0 +1,254 @@ +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Moq; +using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Endpoints.RefreshTokens; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Test; + +public sealed class RefreshTokenEndpointModeTest { + private const string JwtDefaultScheme = "default-cookie"; + private const string CookieDefaultScheme = "default-jwt"; + private const string CookieSessionScheme = "app-cookie"; + private const string OldRefreshToken = "old-refresh-token"; + private const string NewRefreshToken = "new-refresh-token"; + + [Fact] + public async Task JwtRefresh_UsesBodyAndReturnsJwt_EvenWhenDefaultSignInIsCookie() { + var user = NewUser(); + var refresh = NewRefreshService(user); + var jwt = new Mock>(); + jwt.Setup(provider => provider.GenerateTokenAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new Token { AuthenticationToken = "access-token" }); + using var app = CreateApp(AuthenticationSessionMode.Jwt, refresh.Object, jwt.Object); + var context = NewRequest(app, "refresh", OldRefreshToken, asJson: true); + + await InvokeAsync(app, "refresh", context); + + Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); + context.Response.Body.Position = 0; + var response = await JsonSerializer.DeserializeAsync(context.Response.Body, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Equal("access-token", response?.AuthenticationToken); + Assert.Equal(NewRefreshToken, response?.RefreshToken); + refresh.Verify(service => service.RotateAsync(OldRefreshToken, It.IsAny()), Times.Once); + jwt.Verify(provider => provider.GenerateTokenAsync(It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public async Task CookieRefresh_UsesConfiguredCookieScheme_EvenWhenDefaultSignInIsJwt() { + var user = NewUser(); + var refresh = NewRefreshService(user); + using var app = CreateApp(AuthenticationSessionMode.Cookie, refresh.Object); + var context = NewRequest(app, "refresh", OldRefreshToken, asJson: false); + + await InvokeAsync(app, "refresh", context); + + Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); + var setCookie = context.Response.Headers.SetCookie.ToString(); + Assert.Contains("app-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("__Host-runtimeapps-refresh=" + NewRefreshToken, setCookie, StringComparison.Ordinal); + Assert.DoesNotContain("default-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + refresh.Verify(service => service.RotateAsync(OldRefreshToken, It.IsAny()), Times.Once); + } + + [Fact] + public async Task JwtLogout_RevokesBodyCredentialWithoutCookieOperations() { + var refresh = NewRefreshService(NewUser()); + refresh.Setup(service => service.RevokeAsync(OldRefreshToken, It.IsAny())).ReturnsAsync(true); + using var app = CreateApp(AuthenticationSessionMode.Jwt, refresh.Object); + var context = NewRequest(app, "logout", OldRefreshToken, asJson: true); + + await InvokeAsync(app, "logout", context); + + Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); + refresh.Verify(service => service.RevokeAsync(OldRefreshToken, It.IsAny()), Times.Once); + } + + [Fact] + public async Task CookieLogout_RevokesCookieAndSignsOutConfiguredScheme() { + var refresh = NewRefreshService(NewUser()); + refresh.Setup(service => service.RevokeAsync(OldRefreshToken, It.IsAny())).ReturnsAsync(true); + using var app = CreateApp(AuthenticationSessionMode.Cookie, refresh.Object); + var context = NewRequest(app, "logout", OldRefreshToken, asJson: false); + + await InvokeAsync(app, "logout", context); + + Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); + var setCookie = context.Response.Headers.SetCookie.ToString(); + Assert.Contains("app-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("__Host-runtimeapps-refresh=", setCookie, StringComparison.Ordinal); + Assert.DoesNotContain("default-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + refresh.Verify(service => service.RevokeAsync(OldRefreshToken, It.IsAny()), Times.Once); + } + + [Fact] + public async Task JwtLogoutAll_RevokesAllWithoutCookieOperations() { + var user = NewUser(); + var refresh = NewRefreshService(user); + refresh.Setup(service => service.RevokeAllAsync(user.Id, It.IsAny())).ReturnsAsync(2); + using var app = CreateApp(AuthenticationSessionMode.Jwt, refresh.Object); + var context = NewRequest(app, "logout/all", null, asJson: false); + context.User = PrincipalFor(user); + + await InvokeAsync(app, "logout/all", context); + + Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); + refresh.Verify(service => service.RevokeAllAsync(user.Id, It.IsAny()), Times.Once); + } + + [Fact] + public async Task CookieLogoutAll_RevokesAllAndSignsOutConfiguredScheme() { + var user = NewUser(); + var refresh = NewRefreshService(user); + refresh.Setup(service => service.RevokeAllAsync(user.Id, It.IsAny())).ReturnsAsync(2); + using var app = CreateApp(AuthenticationSessionMode.Cookie, refresh.Object); + var context = NewRequest(app, "logout/all", null, asJson: false); + context.User = PrincipalFor(user); + + await InvokeAsync(app, "logout/all", context); + + Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); + var setCookie = context.Response.Headers.SetCookie.ToString(); + Assert.Contains("app-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("__Host-runtimeapps-refresh=", setCookie, StringComparison.Ordinal); + Assert.DoesNotContain("default-cookie=", setCookie, StringComparison.OrdinalIgnoreCase); + refresh.Verify(service => service.RevokeAllAsync(user.Id, It.IsAny()), Times.Once); + } + + private static EndpointHost CreateApp( + AuthenticationSessionMode mode, + IRefreshTokenService refreshService, + IJwtProvider jwtProvider = null) { + var services = new ServiceCollection(); + var wrongDefault = mode == AuthenticationSessionMode.Jwt ? JwtDefaultScheme : CookieDefaultScheme; + var authentication = services.AddAuthentication(options => { + options.DefaultAuthenticateScheme = wrongDefault; + options.DefaultChallengeScheme = wrongDefault; + options.DefaultSignInScheme = wrongDefault; + }); + authentication.AddCookie(JwtDefaultScheme, options => options.Cookie.Name = "default-cookie"); + authentication.AddJwtBearer(CookieDefaultScheme); + authentication.AddCookie(CookieSessionScheme, options => options.Cookie.Name = "app-cookie"); + services.AddLogging(); + services.AddDataProtection().UseEphemeralDataProtectionProvider(); + + var runtime = authentication.AddRuntimeAppsAuthentication(); + runtime.AddRefreshToken(); + if(mode == AuthenticationSessionMode.Jwt) + runtime.UseJwt("jwt", _ => { }); + else + runtime.AddCookieAuthenticationSessionIssuer(options => options.Scheme = CookieSessionScheme); + + var user = NewUser(); + var principal = PrincipalFor(user); + var userManager = new Mock>(); + userManager.Setup(manager => manager.FindByIdAsync(user.Id)).ReturnsAsync(user); + userManager.Setup(manager => manager.GetUserAsync(It.IsAny())).ReturnsAsync(user); + var lockout = new Mock>(); + lockout.Setup(manager => manager.IsLockedOutAsync(user)).ReturnsAsync(false); + var logins = new Mock>(); + logins.Setup(manager => manager.GetLoginsAsync(user)).ReturnsAsync(new List()); + var signIn = new Mock>(); + signIn.Setup(manager => manager.CanSignInAsync(user)).ReturnsAsync(true); + var principalFactory = new Mock>(); + principalFactory.Setup(factory => factory.CreateAsync(user)).ReturnsAsync(principal); + + services.Replace(ServiceDescriptor.Singleton>(userManager.Object)); + services.Replace(ServiceDescriptor.Singleton>(lockout.Object)); + services.Replace(ServiceDescriptor.Singleton>(logins.Object)); + services.Replace(ServiceDescriptor.Singleton>(signIn.Object)); + services.Replace(ServiceDescriptor.Singleton>(principalFactory.Object)); + services.Replace(ServiceDescriptor.Singleton>(refreshService)); + if(jwtProvider != null) + services.Replace(ServiceDescriptor.Singleton>(jwtProvider)); + + var serviceProvider = services.BuildServiceProvider(); + var endpoints = new TestEndpointRouteBuilder(serviceProvider); + endpoints.MapRefreshTokenApi(); + return new EndpointHost(serviceProvider, endpoints); + } + + private static Mock> NewRefreshService(IdentityUser user) { + var refresh = new Mock>(); + refresh.Setup(service => service.RotateAsync(OldRefreshToken, It.IsAny())) + .ReturnsAsync(new RefreshTokenSession { + UserId = user.Id, + SessionId = Guid.NewGuid(), + RefreshToken = NewRefreshToken, + ExpiresAt = DateTimeOffset.UtcNow.AddDays(1) + }); + return refresh; + } + + private static IdentityUser NewUser() => new() { Id = "user-1", EmailConfirmed = true }; + + private static ClaimsPrincipal PrincipalFor(IdentityUser user) => new(new ClaimsIdentity( + new[] { new Claim(ClaimTypes.NameIdentifier, user.Id) }, "test")); + + private static DefaultHttpContext NewRequest(EndpointHost app, string path, string refreshToken, bool asJson) { + var context = new DefaultHttpContext { RequestServices = app.Services }; + context.Request.Method = "POST"; + context.Request.Path = "/" + path; + context.Request.Scheme = "https"; + context.Request.Host = new HostString("api.example.test"); + context.Response.Body = new MemoryStream(); + if(refreshToken != null) { + if(asJson) { + context.Request.ContentType = "application/json"; + context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new RefreshTokenRequest { RefreshToken = refreshToken }))); + } else { + context.Request.Headers.Cookie = "__Host-runtimeapps-refresh=" + refreshToken; + context.Request.Headers.Origin = "https://api.example.test"; + } + } else if(path == "logout/all") { + context.Request.Headers.Origin = "https://api.example.test"; + } + return context; + } + + private static async Task InvokeAsync(EndpointHost app, string route, HttpContext context) { + var endpoint = app.Endpoints.DataSources.SelectMany(source => source.Endpoints).OfType() + .Single(candidate => string.Equals(candidate.RoutePattern.RawText?.Trim('/'), route, StringComparison.OrdinalIgnoreCase)); + context.SetEndpoint(endpoint); + var requestDelegate = endpoint.RequestDelegate ?? throw new InvalidOperationException("Mapped endpoint has no request delegate."); + await requestDelegate(context); + } + + private sealed class EndpointHost : IDisposable { + public EndpointHost(IServiceProvider services, TestEndpointRouteBuilder endpoints) { + Services = services; + Endpoints = endpoints; + } + + public IServiceProvider Services { get; } + public TestEndpointRouteBuilder Endpoints { get; } + public void Dispose() => (Services as IDisposable)?.Dispose(); + } + + private sealed class TestEndpointRouteBuilder : IEndpointRouteBuilder { + public TestEndpointRouteBuilder(IServiceProvider services) => ServiceProvider = services; + + public ICollection DataSources { get; } = new List(); + public IServiceProvider ServiceProvider { get; } + public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider); + } +}