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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,15 @@ Add endpoints (There are more endpoints in samples):
```cs
app.MapGroup("api")
.WithTags("Authentication APIs")
.MapLoginApi<IdentityUser, IdentityRole, string>()
.MapRegisterApi<IdentityUser, IdentityRole, string>();
.MapAuthenticationApi<IdentityUser, IdentityUserDto, string>()
.MapRegistrationApi<IdentityUser, IdentityUserDto, string>();

app.MapGroup("api")
.MapVerificationApi<IdentityUser, IdentityUserDto, string>();

app.MapGroup("api/account")
.WithTags("Account APIs")
.MapAccountApi<IdentityUser, IdentityRole, string>();
.MapAccountManagementApi<IdentityUser, IdentityUserDto, string>();
```

You can add more services and customize services. Also, there are some [samples](./Samples/) in this repository.
Expand Down Expand Up @@ -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<TUser, TKey>()` 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 |
| --- | --- |
Expand Down Expand Up @@ -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<TUser, TKey>()\` 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<TUser, TKey>()\` when you want to expose it.

Register the feature after \`AddVerificationServices()\`:

Expand All @@ -317,7 +320,7 @@ Register a persistent \`IVerificationRequestStore<TKey>\` and an \`IVerification

\`\`\`cs
app.MapGroup("api")
.MapForgotPasswordApi<IdentityUser<int>, int>();
.MapPasswordRecoveryApi<IdentityUser<int>, int>();
\`\`\`

The mapped endpoints are:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,60 +20,48 @@
using RuntimeApps.Authentication.Shared.Models;
namespace RuntimeApps.Authentication.Endpoints.Account {
public static class AccountApiEndpointRouteBuilderExtensions {
public static IEndpointRouteBuilder MapLoginApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
/// <summary>Maps login and configured external-login endpoints only.</summary>
public static IEndpointRouteBuilder MapAuthenticationApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
where TUser : IdentityUser<TKey>
where TUserDto : class
where TKey : IEquatable<TKey> {
var routeGroup = endpoints.MapGroup("");

IEnumerable<IExternalLoginProvider<TUser>> externalLoginProviders = endpoints.ServiceProvider.GetServices<IExternalLoginProvider<TUser>>();
RequireServices(endpoints, "Authentication", typeof(IUserAccountService<TUser>), typeof(IUserMapper<TUser, TUserDto>));
var routeGroup = endpoints.MapGroup("").AllowAnonymous();

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

if(externalLoginProviders?.Any() == true) {
if(endpoints.ServiceProvider.GetService<IServiceProviderIsService>()
?.IsService(typeof(IExternalLoginProvider<TUser>)) == true) {
routeGroup.MapPost("login/external", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService<TUser> userAccountService, [FromServices] IUserMapper<TUser, TUserDto> mapper, HttpContext context) => {
var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token, context.RequestAborted);
if(!result.Succeeded)
return result.CreateValidationProblem();
return TypedResults.Ok(MapResult<TUser, TUserDto, TKey>(result, mapper));
});
}

// Refresh endpoints are exposed only when AddRefreshToken() was used during registration.
if(endpoints.ServiceProvider.GetService<IServiceProviderIsService>()
?.IsService(typeof(IRefreshTokenService<TKey>)) == true) {
endpoints.MapRefreshTokenApi<TUser, TKey>();
}).WithName("Authentication_ExternalLogin").WithTags("Authentication").WithSummary("Log in with an external provider");
}

return endpoints;
}

public static IEndpointRouteBuilder MapRegisterApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
/// <summary>Maps the user-registration endpoint.</summary>
public static IEndpointRouteBuilder MapRegistrationApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
where TUser : IdentityUser<TKey>, new()
where TUserDto : class
where TKey : IEquatable<TKey> {
var serviceAvailability = endpoints.ServiceProvider.GetRequiredService<IServiceProviderIsService>();
var requiredServices = new[] {
RequireServices(endpoints, "Registration",
typeof(IRegistrationService<TUser, TKey>),
typeof(IUserAccountService<TUser>),
typeof(IUserMapper<TUser, TUserDto>),
typeof(IVerificationWorkflowService<TUser, TKey>),
typeof(IVerificationRequestStore<TKey>),
typeof(IVerificationSender<TUser, TKey>),
typeof(IUserAccountService<TUser>),
typeof(IUserMapper<TUser, TUserDto>)
};
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<TUser, TKey>));

var routeGroup = endpoints.MapGroup("");
var routeGroup = endpoints.MapGroup("").AllowAnonymous();

routeGroup.MapPost("register", async Task<Results<Accepted<Result<RegistrationVerificationResponse>>, ValidationProblem>> (
[FromBody] RegisterUserModel<TUserDto> user,
Expand All @@ -88,8 +76,18 @@ public static IEndpointRouteBuilder MapRegisterApi<TUser, TUserDto, TKey>(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;
}

/// <summary>Maps registration verification and resend endpoints.</summary>
public static IEndpointRouteBuilder MapVerificationApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
where TUser : IdentityUser<TKey>, new()
where TUserDto : class
where TKey : IEquatable<TKey> {
RequireServices(endpoints, "Verification", typeof(IRegistrationService<TUser, TKey>), typeof(IUserMapper<TUser, TUserDto>), typeof(IVerificationWorkflowService<TUser, TKey>), typeof(IVerificationRequestStore<TKey>), typeof(IVerificationSender<TUser, TKey>));
var routeGroup = endpoints.MapGroup("").AllowAnonymous();
routeGroup.MapPost("register/verify", async Task<Results<Ok<Result<TUserDto, Token>>, ValidationProblem>> (
[FromBody] VerifyRegistrationModel request,
IRegistrationService<TUser, TKey> registrationService,
Expand All @@ -103,7 +101,7 @@ public static IEndpointRouteBuilder MapRegisterApi<TUser, TUserDto, TKey>(this I
if(!result.Succeeded)
return result.CreateValidationProblem();
return TypedResults.Ok(MapResult<TUser, TUserDto, TKey>(result, mapper));
});
}).WithName("Verification_VerifyRegistration").WithTags("Verification").WithSummary("Verify a registration");

routeGroup.MapPost("register/resend", async Task<Results<Accepted<Result<RegistrationVerificationResponse>>, ValidationProblem>> (
[FromBody] ResendRegistrationVerificationModel request,
Expand All @@ -117,7 +115,7 @@ public static IEndpointRouteBuilder MapRegisterApi<TUser, TUserDto, TKey>(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;
}
Expand Down Expand Up @@ -166,16 +164,18 @@ public static IEndpointRouteBuilder MapAdminUserApi<TUser, TUserDto, TKey>(
return endpoints;
}

public static IEndpointRouteBuilder MapAccountApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
/// <summary>Maps authenticated current-account and password-management endpoints.</summary>
public static IEndpointRouteBuilder MapAccountManagementApi<TUser, TUserDto, TKey>(this IEndpointRouteBuilder endpoints)
where TUser : IdentityUser<TKey>
where TUserDto : class
where TKey : IEquatable<TKey> {
RequireServices(endpoints, "Account management", typeof(IUserManager<TUser>), typeof(IUserMapper<TUser, TUserDto>), typeof(IUserPasswordManager<TUser>));
var authorizedRouteGroup = endpoints.MapGroup("").RequireAuthorization();

authorizedRouteGroup.MapGet("/", async (IUserManager<TUser> userManager, HttpContext httpContext, IUserMapper<TUser, TUserDto> 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<Results<Ok, ValidationProblem>> ([FromBody] ChangePasswordModel input, IUserManager<TUser> userManager, IUserPasswordManager<TUser> passwordManager, HttpContext httpContext, IServiceProvider services) => {
var user = await userManager.GetUserAsync(httpContext.User);
Expand All @@ -191,7 +191,7 @@ public static IEndpointRouteBuilder MapAccountApi<TUser, TUserDto, TKey>(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<Results<Ok, ValidationProblem>> ([FromBody] string password, IUserManager<TUser> userManager, IUserPasswordManager<TUser> passwordManager, HttpContext httpContext, IServiceProvider services) => {
var user = await userManager.GetUserAsync(httpContext.User);
Expand All @@ -207,11 +207,18 @@ public static IEndpointRouteBuilder MapAccountApi<TUser, TUserDto, TKey>(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<IServiceProviderIsService>();
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<TUserDto, Token> MapResult<TUser, TUserDto, TKey>(Result<TUser, Token> result, IUserMapper<TUser, TUserDto> mapper)
where TUser : IdentityUser<TKey>
where TUserDto : class
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ public static class ForgotPasswordApiEndpointRouteBuilderExtensions {
/// <summary>
/// Maps the optional password-recovery endpoints. Call this explicitly to expose them.
/// </summary>
public static IEndpointRouteBuilder MapForgotPasswordApi<TUser, TKey>(
public static IEndpointRouteBuilder MapPasswordRecoveryApi<TUser, TKey>(
this IEndpointRouteBuilder endpoints)
where TUser : Microsoft.AspNetCore.Identity.IdentityUser<TKey>
where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(endpoints);

var availability = endpoints.ServiceProvider.GetRequiredService<IServiceProviderIsService>();
var availability = endpoints.ServiceProvider.GetService<IServiceProviderIsService>();
if(availability == null)
throw new InvalidOperationException("Password recovery endpoints require IServiceProviderIsService to validate their dependencies.");
var requiredServices = new[] {
typeof(IForgotPasswordService<TUser, TKey>),
typeof(IForgotPasswordVerificationWorkflow<TUser, TKey>),
Expand All @@ -36,14 +38,14 @@ public static IEndpointRouteBuilder MapForgotPasswordApi<TUser, TKey>(
"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<Ok<ForgotPasswordResponse>> (
[FromBody] ForgotPasswordRequestModel request,
IForgotPasswordService<TUser, TKey> 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<Results<Ok, ValidationProblem>> (
[FromBody] ResetPasswordModel request,
Expand All @@ -59,7 +61,7 @@ public static IEndpointRouteBuilder MapForgotPasswordApi<TUser, TKey>(
if(!result.Succeeded)
return result.CreateValidationProblem();
return TypedResults.Ok();
}).WithName("ResetPassword");
}).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password");

return endpoints;
}
Expand Down
Loading
Loading