diff --git a/ReadMe.md b/ReadMe.md index c3c6a7f..1ff55f5 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -79,12 +79,15 @@ Add endpoints (There are more endpoints in samples): ```cs app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi() - .MapRegisterApi(); + .MapAuthenticationApi() + .MapRegistrationApi(); + +app.MapGroup("api") + .MapVerificationApi(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi(); + .MapAccountManagementApi(); ``` You can add more services and customize services. Also, there are some [samples](./Samples/) in this repository. @@ -201,7 +204,7 @@ Create and apply an EF Core migration after adding the entity. The EF store requ ### Endpoints -When `AddRefreshToken()` is registered, `MapLoginApi` also maps the following endpoints. The refresh endpoint is automatically rate-limited to 30 requests per minute per remote IP; configure `RefreshRequestsPerMinute` to change the limit. The limiter is in-process; multi-instance deployments should also enforce a shared limit at the gateway or through a distributed rate-limiting layer. When running behind a reverse proxy, configure trusted forwarded headers so the partition key reflects the actual client address. No additional rate-limiting middleware setup is required. +Map sessions explicitly with `MapSessionApi()` after registering `AddRefreshToken()`. The refresh endpoint is automatically rate-limited to 30 requests per minute per remote IP; configure `RefreshRequestsPerMinute` to change the limit. The limiter is in-process; multi-instance deployments should also enforce a shared limit at the gateway or through a distributed rate-limiting layer. When running behind a reverse proxy, configure trusted forwarded headers so the partition key reflects the actual client address. No additional rate-limiting middleware setup is required. | Endpoint | Behavior | | --- | --- | @@ -299,7 +302,7 @@ This is a breaking major-version change. Remove calls to the old immediate-token ## Optional forgot-password API -Password recovery is an optional feature. It reuses the verification-request store, protected verifier, sender, expiration, send limits, and one-time request consumption. It is not mapped by \`MapLoginApi\`, \`MapRegisterApi\`, or \`MapAccountApi\`; explicitly call \`MapForgotPasswordApi()\` only when you want to expose it. +Password recovery is an optional feature. It reuses the verification-request store, protected verifier, sender, expiration, send limits, and one-time request consumption. It is mapped independently with \`MapPasswordRecoveryApi()\` when you want to expose it. Register the feature after \`AddVerificationServices()\`: @@ -317,7 +320,7 @@ Register a persistent \`IVerificationRequestStore\` and an \`IVerification \`\`\`cs app.MapGroup("api") - .MapForgotPasswordApi, int>(); + .MapPasswordRecoveryApi, int>(); \`\`\` The mapped endpoints are: diff --git a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs index 0fca15b..90760f2 100644 --- a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs @@ -20,60 +20,48 @@ using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Endpoints.Account { public static class AccountApiEndpointRouteBuilderExtensions { - public static IEndpointRouteBuilder MapLoginApi(this IEndpointRouteBuilder endpoints) + /// Maps login and configured external-login endpoints only. + public static IEndpointRouteBuilder MapAuthenticationApi(this IEndpointRouteBuilder endpoints) where TUser : IdentityUser where TUserDto : class where TKey : IEquatable { - var routeGroup = endpoints.MapGroup(""); - - IEnumerable> externalLoginProviders = endpoints.ServiceProvider.GetServices>(); + RequireServices(endpoints, "Authentication", typeof(IUserAccountService), typeof(IUserMapper)); + var routeGroup = endpoints.MapGroup("").AllowAnonymous(); 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)); - }); + }).WithName("Authentication_Login").WithTags("Authentication").WithSummary("Log in"); - if(externalLoginProviders?.Any() == true) { + if(endpoints.ServiceProvider.GetService() + ?.IsService(typeof(IExternalLoginProvider)) == true) { 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)); - }); - } - - // Refresh endpoints are exposed only when AddRefreshToken() was used during registration. - if(endpoints.ServiceProvider.GetService() - ?.IsService(typeof(IRefreshTokenService)) == true) { - endpoints.MapRefreshTokenApi(); + }).WithName("Authentication_ExternalLogin").WithTags("Authentication").WithSummary("Log in with an external provider"); } return endpoints; } - public static IEndpointRouteBuilder MapRegisterApi(this IEndpointRouteBuilder endpoints) + /// Maps the user-registration endpoint. + public static IEndpointRouteBuilder MapRegistrationApi(this IEndpointRouteBuilder endpoints) where TUser : IdentityUser, new() where TUserDto : class where TKey : IEquatable { - var serviceAvailability = endpoints.ServiceProvider.GetRequiredService(); - var requiredServices = new[] { + RequireServices(endpoints, "Registration", typeof(IRegistrationService), + typeof(IUserAccountService), + typeof(IUserMapper), typeof(IVerificationWorkflowService), typeof(IVerificationRequestStore), - typeof(IVerificationSender), - typeof(IUserAccountService), - typeof(IUserMapper) - }; - var missingServices = requiredServices.Where(type => !serviceAvailability.IsService(type)).ToArray(); - if(missingServices.Length > 0) - throw new InvalidOperationException( - "Registration endpoints require verification services, a persistent verification request store, " + - "a verification sender, an account service, and a user mapper. Missing: " + - string.Join(", ", missingServices.Select(type => type.Name))); + typeof(IVerificationSender)); - var routeGroup = endpoints.MapGroup(""); + var routeGroup = endpoints.MapGroup("").AllowAnonymous(); routeGroup.MapPost("register", async Task>, ValidationProblem>> ( [FromBody] RegisterUserModel user, @@ -88,8 +76,18 @@ public static IEndpointRouteBuilder MapRegisterApi(this I if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Accepted((string)null, result); - }); + }).WithName("Registration_Register").WithTags("Registration").WithSummary("Register a user"); + return endpoints; + } + + /// Maps registration verification and resend endpoints. + public static IEndpointRouteBuilder MapVerificationApi(this IEndpointRouteBuilder endpoints) + where TUser : IdentityUser, new() + where TUserDto : class + where TKey : IEquatable { + RequireServices(endpoints, "Verification", typeof(IRegistrationService), typeof(IUserMapper), typeof(IVerificationWorkflowService), typeof(IVerificationRequestStore), typeof(IVerificationSender)); + var routeGroup = endpoints.MapGroup("").AllowAnonymous(); routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( [FromBody] VerifyRegistrationModel request, IRegistrationService registrationService, @@ -103,7 +101,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(MapResult(result, mapper)); - }); + }).WithName("Verification_VerifyRegistration").WithTags("Verification").WithSummary("Verify a registration"); routeGroup.MapPost("register/resend", async Task>, ValidationProblem>> ( [FromBody] ResendRegistrationVerificationModel request, @@ -117,7 +115,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Accepted((string)null, result); - }); + }).WithName("Verification_ResendRegistration").WithTags("Verification").WithSummary("Resend registration verification"); return endpoints; } @@ -166,16 +164,18 @@ public static IEndpointRouteBuilder MapAdminUserApi( return endpoints; } - public static IEndpointRouteBuilder MapAccountApi(this IEndpointRouteBuilder endpoints) + /// Maps authenticated current-account and password-management endpoints. + public static IEndpointRouteBuilder MapAccountManagementApi(this IEndpointRouteBuilder endpoints) where TUser : IdentityUser where TUserDto : class where TKey : IEquatable { + RequireServices(endpoints, "Account management", typeof(IUserManager), typeof(IUserMapper), typeof(IUserPasswordManager)); var authorizedRouteGroup = endpoints.MapGroup("").RequireAuthorization(); authorizedRouteGroup.MapGet("/", async (IUserManager userManager, HttpContext httpContext, IUserMapper mapper) => { var user = await userManager.GetUserAsync(httpContext.User); return user != null ? mapper.ToDto(user) : null; - }); + }).WithName("AccountManagement_Get").WithTags("Account management").WithSummary("Get the current account"); authorizedRouteGroup.MapPost("password/change", async Task> ([FromBody] ChangePasswordModel input, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { var user = await userManager.GetUserAsync(httpContext.User); @@ -191,7 +191,7 @@ public static IEndpointRouteBuilder MapAccountApi(this IE await refreshTokenService.RevokeAllAsync(user.Id, httpContext.RequestAborted); return TypedResults.Ok(); - }); + }).WithName("AccountManagement_ChangePassword").WithTags("Account management").WithSummary("Change the current password"); authorizedRouteGroup.MapPost("password", async Task> ([FromBody] string password, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { var user = await userManager.GetUserAsync(httpContext.User); @@ -207,11 +207,18 @@ public static IEndpointRouteBuilder MapAccountApi(this IE await refreshTokenService.RevokeAllAsync(user.Id, httpContext.RequestAborted); return TypedResults.Ok(); - }); + }).WithName("AccountManagement_AddPassword").WithTags("Account management").WithSummary("Add a password to the current account"); return endpoints; } + private static void RequireServices(IEndpointRouteBuilder endpoints, string feature, params Type[] services) { + var availability = endpoints.ServiceProvider.GetService(); + var missing = availability == null ? services : services.Where(service => !availability.IsService(service)).ToArray(); + if(missing.Length > 0) + throw new InvalidOperationException($"{feature} endpoints require these registered services: {string.Join(", ", missing.Select(service => service.Name))}."); + } + private static Result MapResult(Result result, IUserMapper mapper) where TUser : IdentityUser where TUserDto : class diff --git a/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs index d155cc8..2143985 100644 --- a/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs @@ -14,13 +14,15 @@ public static class ForgotPasswordApiEndpointRouteBuilderExtensions { /// /// Maps the optional password-recovery endpoints. Call this explicitly to expose them. /// - public static IEndpointRouteBuilder MapForgotPasswordApi( + public static IEndpointRouteBuilder MapPasswordRecoveryApi( this IEndpointRouteBuilder endpoints) where TUser : Microsoft.AspNetCore.Identity.IdentityUser where TKey : IEquatable { ArgumentNullException.ThrowIfNull(endpoints); - var availability = endpoints.ServiceProvider.GetRequiredService(); + var availability = endpoints.ServiceProvider.GetService(); + if(availability == null) + throw new InvalidOperationException("Password recovery endpoints require IServiceProviderIsService to validate their dependencies."); var requiredServices = new[] { typeof(IForgotPasswordService), typeof(IForgotPasswordVerificationWorkflow), @@ -36,14 +38,14 @@ public static IEndpointRouteBuilder MapForgotPasswordApi( "a persistent verification request store, and a verification sender. Missing: " + string.Join(", ", missing.Select(type => type.Name))); - var group = endpoints.MapGroup(""); + var group = endpoints.MapGroup("").AllowAnonymous(); group.MapPost("forgot-password", async Task> ( [FromBody] ForgotPasswordRequestModel request, IForgotPasswordService service, HttpContext httpContext) => { var result = await service.RequestAsync(request?.Email, httpContext.RequestAborted); return TypedResults.Ok(result); - }).WithName("ForgotPassword"); + }).WithName("PasswordRecovery_Forgot").WithTags("Password recovery").WithSummary("Request a password reset"); group.MapPost("reset-password", async Task> ( [FromBody] ResetPasswordModel request, @@ -59,7 +61,7 @@ public static IEndpointRouteBuilder MapForgotPasswordApi( if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); - }).WithName("ResetPassword"); + }).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password"); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs index b78501c..297a3e5 100644 --- a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -16,15 +16,16 @@ namespace RuntimeApps.Authentication.Endpoints.RefreshTokens { public static class RefreshTokenApiEndpointRouteBuilderExtensions { /// - /// Maps refresh, current-session logout, and logout-all endpoints. This is called automatically - /// by MapLoginApi when AddRefreshToken has registered the refresh-token service. + /// Maps refresh, current-session logout, and logout-all endpoints. /// - public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpointRouteBuilder endpoints) + public static IEndpointRouteBuilder MapSessionApi(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 availability = endpoints.ServiceProvider.GetService(); + if(availability?.IsService(typeof(IRefreshTokenService)) != true) + throw new InvalidOperationException("Session endpoints require the refresh-token service. Register refresh-token functionality first."); + if(availability.IsService(typeof(IAuthenticationSessionIssuer)) != true) + throw new InvalidOperationException("Session endpoints require exactly one explicitly registered authentication session issuer."); var routes = endpoints.MapGroup(""); @@ -102,6 +103,9 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, } }) .Accepts(true, "application/json") + .AllowAnonymous() + .WithName("Session_Refresh") + .WithTags("Sessions") .WithSummary("Refresh the current session") .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication."); @@ -128,6 +132,9 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, return Results.NoContent(); }) .Accepts(true, "application/json") + .AllowAnonymous() + .WithName("Session_Logout") + .WithTags("Sessions") .WithSummary("Log out the current session") .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication."); @@ -151,7 +158,7 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, if(isCookie) DeleteRefreshCookie(context, options.Value); return Results.NoContent(); - }).RequireAuthorization(); + }).RequireAuthorization().WithName("Session_LogoutAll").WithTags("Sessions").WithSummary("Log out all sessions"); return endpoints; } diff --git a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/Program.cs b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/Program.cs index ba90669..ebdc9d7 100644 --- a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/Program.cs @@ -104,12 +104,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>() - .MapRegisterApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapGroup("api/user") .WithTags("User View") diff --git a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/ReadMe.md index 91d7bed..b14fa12 100644 --- a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/ReadMe.md @@ -20,12 +20,11 @@ In Asp.Net core identity users can have claims as same as roles. So each user ha app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>() - .MapRegisterApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapGroup("api/user") .WithTags("User View") diff --git a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs index 8f0b465..56b9f26 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/Program.cs @@ -73,12 +73,13 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>() - .MapRegisterApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/user") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); + +app.MapGroup("api/session").MapSessionApi, int>(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/ReadMe.md index 6acca09..9f4c10e 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample.CookieAuthentication/ReadMe.md @@ -12,7 +12,7 @@ The sample enables refresh tokens explicitly with `AddRefreshToken()` and regist }) ``` -The `MapLoginApi` extension automatically maps `POST /api/refresh`, `POST /api/logout`, and the authenticated `POST /api/logout/all` endpoints when refresh-token support is enabled. Cookie refresh credentials are stored in a Secure, HttpOnly cookie. For cross-origin clients, configure the exact allowed origins and review the application's CORS and CSRF policy. +Map sessions explicitly with `app.MapGroup("api/session").MapSessionApi, int>()` after registering refresh-token support. Refresh and current-session logout use refresh-token credentials; logout-all requires an authenticated user. Cookie refresh credentials are stored in a Secure, HttpOnly cookie. For cross-origin clients, configure the exact allowed origins and review the application's CORS and CSRF policy. Each successful login creates an independent session. Refresh-token reuse revokes only the affected session family; logout-all revokes all sessions for the authenticated user. diff --git a/Samples/RuntimeApps.Authentication.Sample.CustomClaim/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CustomClaim/Program.cs index f3822c7..d8efc3e 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CustomClaim/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CustomClaim/Program.cs @@ -90,12 +90,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>() - .MapRegisterApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample.CustomModel/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CustomModel/Program.cs index 029f18d..1f33fb0 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CustomModel/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CustomModel/Program.cs @@ -117,12 +117,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi() - .MapRegisterApi(); + .MapAuthenticationApi(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi(); + .MapAccountManagementApi(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample.CustomStore/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CustomStore/Program.cs index 6a9dead..2abc213 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CustomStore/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CustomStore/Program.cs @@ -70,12 +70,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi() - .MapRegisterApi(); + .MapAuthenticationApi(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi(); + .MapAccountManagementApi(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample.CustomValidation/Program.cs b/Samples/RuntimeApps.Authentication.Sample.CustomValidation/Program.cs index 0a04987..8464583 100644 --- a/Samples/RuntimeApps.Authentication.Sample.CustomValidation/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.CustomValidation/Program.cs @@ -98,12 +98,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi() - .MapRegisterApi(); + .MapAuthenticationApi(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi(); + .MapAccountManagementApi(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/Program.cs b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/Program.cs index 0408569..3544056 100644 --- a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/Program.cs @@ -98,11 +98,11 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapGroup("api/user") .WithTags("User View") @@ -117,7 +117,6 @@ app.MapGroup("api/user") .WithTags("User Manage") .RequireAuthorization(config => config.RequireRole(RoleConsts.UserManagerRole)) - .MapRegisterApi, IdentityUserDto, int>() .MapUserRoleGetApi>() .MapUserRoleManageApi>(); diff --git a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/ReadMe.md index 9381ee1..53747f9 100644 --- a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/ReadMe.md @@ -8,11 +8,11 @@ ASP.Net core has deferent ways to manage authorization and one of them is [Role- app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>(); + .MapAuthenticationApi, IdentityUserDto, int>(); app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapGroup("api/user") .WithTags("User View") @@ -27,7 +27,6 @@ app.MapGroup("api/role") app.MapGroup("api/user") .WithTags("User Manage") .RequireAuthorization(config => config.RequireRole(RoleConsts.UserManagerRole)) - .MapRegisterApi, IdentityUserDto, int>() .MapUserRoleGetApi>() .MapUserRoleManageApi>(); diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index 72ba48d..bb106da 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -126,9 +126,10 @@ app.MapGroup("api") .WithTags("Authentication APIs") - .MapLoginApi, IdentityUserDto, int>() - .MapRegisterApi, IdentityUserDto, int>() - .MapForgotPasswordApi, int>(); + .MapAuthenticationApi, IdentityUserDto, int>() + .MapRegistrationApi, IdentityUserDto, int>() + .MapVerificationApi, IdentityUserDto, int>() + .MapPasswordRecoveryApi, int>(); app.MapGroup("api") .WithTags("Administrator APIs") @@ -136,7 +137,7 @@ app.MapGroup("api/account") .WithTags("Account APIs") - .MapAccountApi, IdentityUserDto, int>(); + .MapAccountManagementApi, IdentityUserDto, int>(); app.MapControllerRoute( name: "default", diff --git a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md index 00d9e53..900f818 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -95,9 +95,10 @@ By default a mapper registered with `AddUserMapper()` is scop Endpoint registration is unchanged apart from the DTO type argument, for example: ```cs -app.MapGroup("api").MapLoginApi() - .MapRegisterApi(); -app.MapGroup("api/account").MapAccountApi(); +app.MapGroup("api").MapAuthenticationApi() + .MapRegistrationApi(); +app.MapGroup("api").MapVerificationApi(); +app.MapGroup("api/account").MapAccountManagementApi(); ``` @@ -153,7 +154,7 @@ The endpoint is mapped separately from the other authentication endpoints: \`\`\`cs app.MapGroup("api") - .MapForgotPasswordApi, int>(); + .MapPasswordRecoveryApi, int>(); \`\`\` The frontend receives the reset handle and token in the URL fragment, removes them from the address bar immediately, and submits them with the new password to \`POST /api/reset-password\`. Loading the frontend link does not consume the credential. In code mode, the API response supplies the handle and the email supplies the code. In link mode, the sender uses `context.CreateVerificationUrl(token)` to create the frontend reset link; no handle is returned in the API response. diff --git a/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs index c1e2a97..a4e12c0 100644 --- a/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/AuthenticationSessionIssuerTest.cs @@ -217,9 +217,10 @@ public void SessionIssuerMode_IsExplicitAndIndependentOfDefaultSignInScheme() { [Fact] public void RefreshEndpoints_RequireExplicitIssuerRegistration() { var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton>(new Mock>().Object); using var app = builder.Build(); - var error = Assert.Throws(() => app.MapRefreshTokenApi()); + var error = Assert.Throws(() => app.MapSessionApi()); Assert.Contains("exactly one explicitly registered authentication session issuer", error.Message); } diff --git a/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs b/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs new file mode 100644 index 0000000..70f67db --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs @@ -0,0 +1,103 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using RuntimeApps.Authentication.Endpoints.Account; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.Registration.Contracts; +using RuntimeApps.Authentication.Features.Verification.Contracts; +using RuntimeApps.Authentication.Identity.Contracts; + +namespace RuntimeApps.Authentication.Test; + +public sealed class FeatureEndpointMappingTest { + [Fact] + public void AuthenticationMapping_DoesNotMapSessionEndpoints() { + using var host = CreateHost(includeVerificationDependencies: false); + + host.Endpoints.MapGroup("api/auth") + .MapAuthenticationApi, TestUserDto, int>(); + + var endpoint = Assert.Single(Endpoints(host)); + Assert.Equal("api/auth/login", ((RouteEndpoint)endpoint).RoutePattern.RawText); + Assert.IsAssignableFrom(endpoint.Metadata.GetMetadata()); + } + + [Fact] + public void RegistrationMapping_IsIndependentAndAnonymous() { + using var host = CreateHost(includeVerificationDependencies: true); + + host.Endpoints.MapGroup("api/register") + .MapRegistrationApi, TestUserDto, int>(); + + var endpoint = Assert.Single(Endpoints(host)); + Assert.Equal("api/register/register", ((RouteEndpoint)endpoint).RoutePattern.RawText); + Assert.IsAssignableFrom(endpoint.Metadata.GetMetadata()); + Assert.Equal("Registration_Register", endpoint.Metadata.GetMetadata()?.EndpointName); + } + + [Fact] + public void VerificationMapping_UsesTheChosenDtoAndMapsOnlyVerificationRoutes() { + using var host = CreateHost(includeVerificationDependencies: true); + + host.Endpoints.MapGroup("api/register") + .MapVerificationApi, TestUserDto, int>(); + + var endpoints = Endpoints(host).OfType().ToArray(); + Assert.Equal(new[] { "api/register/register/resend", "api/register/register/verify" }, + endpoints.Select(endpoint => endpoint.RoutePattern.RawText).OrderBy(route => route, StringComparer.Ordinal)); + Assert.All(endpoints, endpoint => Assert.IsAssignableFrom(endpoint.Metadata.GetMetadata())); + Assert.Equal(2, endpoints.Select(endpoint => endpoint.Metadata.GetMetadata()?.EndpointName).Distinct().Count()); + } + + [Fact] + public void RegistrationMapping_ReportsMissingDependenciesAtMappingTime() { + var services = new ServiceCollection(); + services.AddSingleton(Mock.Of, int>>()); + services.AddSingleton(Mock.Of>>()); + services.AddSingleton(Mock.Of, TestUserDto>>()); + using var host = new TestHost(services.BuildServiceProvider()); + + var error = Assert.Throws(() => host.Endpoints + .MapRegistrationApi, TestUserDto, int>()); + + Assert.Contains("Registration", error.Message, StringComparison.Ordinal); + Assert.Contains("IVerificationWorkflowService", error.Message, StringComparison.Ordinal); + Assert.Contains("IVerificationRequestStore", error.Message, StringComparison.Ordinal); + Assert.Contains("IVerificationSender", error.Message, StringComparison.Ordinal); + } + + private static TestHost CreateHost(bool includeVerificationDependencies) { + var services = new ServiceCollection(); + services.AddSingleton(Mock.Of, int>>()); + services.AddSingleton(Mock.Of>>()); + services.AddSingleton(Mock.Of, TestUserDto>>()); + if(includeVerificationDependencies) { + services.AddSingleton(Mock.Of, int>>()); + services.AddSingleton(Mock.Of>()); + services.AddSingleton(Mock.Of, int>>()); + } + return new TestHost(services.BuildServiceProvider()); + } + + private static Endpoint[] Endpoints(TestHost host) => host.Endpoints.DataSources + .SelectMany(source => source.Endpoints).ToArray(); + + public sealed class TestUserDto { } + + private sealed class TestHost : IDisposable { + public TestHost(IServiceProvider services) => Endpoints = new TestEndpointRouteBuilder(services); + public TestEndpointRouteBuilder Endpoints { get; } + public void Dispose() => (Endpoints.ServiceProvider 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); + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs b/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs index cd25804..08a6f8e 100644 --- a/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/RefreshTokenEndpointModeTest.cs @@ -183,7 +183,7 @@ private static EndpointHost CreateApp( var serviceProvider = services.BuildServiceProvider(); var endpoints = new TestEndpointRouteBuilder(serviceProvider); - endpoints.MapRefreshTokenApi(); + endpoints.MapSessionApi(); return new EndpointHost(serviceProvider, endpoints); }