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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ Protect personal data | Protect personal user data in database by encrypt user d

## Getting Started

### Request body contracts

Role assignment routes accept a named request object such as `{ "roles": ["Admin"] }` rather than a bare string array. Bulk user-claim routes accept `{ "claims": [{ "type": "department", "value": "finance" }] }`. Role create and update routes accept `{ "role": { ... } }`; the nested role payload uses the consumer's configured role type so custom role fields remain available. These request shapes are versioned API changes for clients of those routes. Single-claim requests continue to use the named `ClaimDto` body, and the authentication, registration, verification, and password routes use named request DTOs.

An external identity with an untrusted email claim is rejected with the same generic authentication failure whether that email matches an existing account or not. An existing account is linked only when the configured email trust policy approves the provider claim. Identity operations do not expose cancellation overloads; endpoint handlers check request cancellation before starting them and finish in-flight writes. Identity provides no transaction spanning user creation and external-login linking, so if linking fails after creation the valid account remains; retrying with the same trusted provider can link it. The service does not delete or unlink records that a concurrent operation may already be using.

`IUserManager<TUser>` provides user lookup, create, update, delete, and principal lookup operations. For services that need specific capabilities, inject focused contracts such as `IUserPasswordManager<TUser>`, `IUserEmailManager<TUser>`, `IUserRoleManager<TUser>`, or `IUserClaimManager<TUser>`. `AddRuntimeAppsAuthentication<TUser, TRole, TKey>()` registers these contracts to the same scoped `RuntimeAppsUserManager<TUser>` instance. The concrete manager remains customizable: derive from `RuntimeAppsUserManager<TUser>` and register it with `.AddUserManager<YourUserManager>()` after calling `AddRuntimeAppsAuthentication`. A manager registered directly as `UserManager<TUser>` before the builder must also derive from `RuntimeAppsUserManager<TUser>` to share the focused interfaces.

To use this library do the steps:
Expand Down Expand Up @@ -293,7 +299,7 @@ External provider login does not require a second email challenge by default. Se

External authentication and email confirmation remain separate. The default trust policy accepts verified Google Gmail/Googlemail addresses and verified Google Workspace addresses when the signed hosted-domain claim matches the email domain. Facebook and Microsoft email claims are not trusted by default. Developers can replace `IExternalLoginEmailTrustPolicy<TUser>`.

External identities are not automatically linked to an existing local account based on a matching email address. Linking must be initiated from an authenticated account-management flow.
When the configured trust policy approves a provider's email claim, external login may automatically link that identity to a local account with the same email. Matching email alone is never sufficient: untrusted or unverified claims are rejected before the account lookup. Applications that do not want trusted-email auto-linking should use a trust policy that approves no claims and provide linking through an authenticated account-management flow.

### Migration note

Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ public static IEndpointRouteBuilder MapPasswordRecoveryApi<TUser, TKey>(
HttpContext httpContext) => {
var result = await service.RequestAsync(request?.Email, httpContext.RequestAborted);
return TypedResults.Ok(result);
}).WithName("PasswordRecovery_Forgot").WithTags("Password recovery").WithSummary("Request a password reset");
}).WithName("PasswordRecovery_Forgot").WithTags("Password recovery").WithSummary("Request a password reset")
.Produces<ForgotPasswordResponse>(StatusCodes.Status200OK);

group.MapPost("reset-password", async Task<Results<Ok, ValidationProblem>> (
group.MapPost("reset-password", async Task<IResult> (
[FromBody] ResetPasswordModel request,
IForgotPasswordService<TUser, TKey> service,
HttpContext httpContext) => {
Expand All @@ -59,9 +60,11 @@ public static IEndpointRouteBuilder MapPasswordRecoveryApi<TUser, TKey>(
request.VerificationHandle, request.Credential, request.NewPassword,
httpContext.RequestAborted);
if(!result.Succeeded)
return result.CreateValidationProblem();
return result.CreatePublicError();
return TypedResults.Ok();
}).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password");
}).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password")
.Produces(StatusCodes.Status200OK)
.ProducesValidationProblem(StatusCodes.Status400BadRequest);

return endpoints;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
Expand All @@ -13,6 +14,7 @@
using RuntimeApps.Authentication.Features.Account.Models;
using RuntimeApps.Authentication.Features.Account.Contracts;
using RuntimeApps.Authentication.Identity.Contracts;
using RuntimeApps.Authentication.Shared.Models;
namespace RuntimeApps.Authentication.Endpoints.RefreshTokens {
public static class RefreshTokenApiEndpointRouteBuilderExtensions {
/// <summary>
Expand Down Expand Up @@ -48,8 +50,10 @@ public static IEndpointRouteBuilder MapSessionApi<TUser, TKey>(this IEndpointRou
var mode = GetSessionMode(sessionIssuers);
var isCookie = mode == AuthenticationSessionMode.Cookie;
RefreshTokenRequest request = null;
if(!isCookie && context.Request.HasJsonContentType())
request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted);
if(!isCookie && context.Request.HasJsonContentType()) {
try { request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted); }
catch(JsonException) { return Results.Problem(statusCode: StatusCodes.Status400BadRequest, title: "Invalid request", detail: "The request body is invalid."); }
}
if(isCookie && !IsAllowedOrigin(context, options.Value))
return Results.StatusCode(StatusCodes.Status403Forbidden);

Expand All @@ -63,7 +67,7 @@ public static IEndpointRouteBuilder MapSessionApi<TUser, TKey>(this IEndpointRou

var user = await userManager.FindByIdAsync(Convert.ToString(session.UserId, System.Globalization.CultureInfo.InvariantCulture));
if(user == null) {
await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted);
await refreshTokenService.RevokeAsync(session.RefreshToken, CancellationToken.None);
return Results.Unauthorized();
}

Expand All @@ -73,7 +77,7 @@ public static IEndpointRouteBuilder MapSessionApi<TUser, TKey>(this IEndpointRou
(hasExternalLogin && !verificationOptions.Value.RequireEmailVerificationForExternalLogins);
if(isLockedOut || !emailPolicyAllowsSignIn ||
(user.EmailConfirmed && !await signInManager.CanSignInAsync(user))) {
await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted);
await refreshTokenService.RevokeAsync(session.RefreshToken, CancellationToken.None);
return Results.Unauthorized();
}

Expand Down Expand Up @@ -107,7 +111,14 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal,
.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.");
.WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication.")
.Produces<Token>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status429TooManyRequests)
.ProducesProblem(StatusCodes.Status500InternalServerError);

routes.MapPost("logout", async Task<IResult> (HttpContext context,
IRefreshTokenService<TKey> refreshTokenService,
Expand All @@ -116,8 +127,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal,
IEnumerable<IAuthenticationSessionIssuer<TUser>> sessionIssuers) => {
var isCookie = GetSessionMode(sessionIssuers) == AuthenticationSessionMode.Cookie;
RefreshTokenRequest request = null;
if(!isCookie && context.Request.HasJsonContentType())
request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted);
if(!isCookie && context.Request.HasJsonContentType()) {
try { request = await context.Request.ReadFromJsonAsync<RefreshTokenRequest>(context.RequestAborted); }
catch(JsonException) { return Results.Problem(statusCode: StatusCodes.Status400BadRequest, title: "Invalid request", detail: "The request body is invalid."); }
}
if(isCookie && !IsAllowedOrigin(context, options.Value))
return Results.StatusCode(StatusCodes.Status403Forbidden);

Expand All @@ -136,7 +149,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal,
.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.");
.WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication.")
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status403Forbidden);

routes.MapPost("logout/all", async Task<IResult> (HttpContext context,
IUserManager<TUser> userManager,
Expand All @@ -158,7 +174,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal,
if(isCookie)
DeleteRefreshCookie(context, options.Value);
return Results.NoContent();
}).RequireAuthorization().WithName("Session_LogoutAll").WithTags("Sessions").WithSummary("Log out all sessions");
}).RequireAuthorization().WithName("Session_LogoutAll").WithTags("Sessions").WithSummary("Log out all sessions")
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden);

return endpoints;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;

namespace RuntimeApps.Authentication.Endpoints.Roles.Models {
/// <summary>
/// Request body for role creation and updates. The generic payload preserves consumer-defined
/// role fields while keeping the public operation envelope explicit.
/// </summary>
public sealed record RoleRequest<TRole>([property: Required] TRole Role) where TRole : class;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,34 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using RuntimeApps.Authentication.Identity.Contracts;
using RuntimeApps.Authentication.Endpoints.Roles.Models;
using RuntimeApps.Authentication.Shared.Extensions;
namespace RuntimeApps.Authentication.Endpoints.Roles {
public static class RoleApiEndpointRouteBuilderExtensions {
public static IEndpointRouteBuilder MapRoleGetApi<TRole>(this IEndpointRouteBuilder endpoints)
where TRole : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapGet("{roleId}", async Task<TRole> ([FromRoute] string roleId, IRoleManager<TRole> roleManager) => {
return await roleManager.FindByIdAsync(roleId);
});
routeGroup.MapGet("{roleId}", async Task<IResult> ([FromRoute] string roleId, IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
cancellationToken.ThrowIfCancellationRequested();
var role = await roleManager.FindByIdAsync(roleId);
cancellationToken.ThrowIfCancellationRequested();
return role == null ? TypedResults.NotFound() : TypedResults.Ok(role);
}).Produces<TRole>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);

routeGroup.MapGet("name/{roleName}", async Task<TRole> ([FromRoute] string roleName, IRoleManager<TRole> roleManager) => {
return await roleManager.FindByNameAsync(roleName);
});
routeGroup.MapGet("name/{roleName}", async Task<IResult> ([FromRoute] string roleName, IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
cancellationToken.ThrowIfCancellationRequested();
var role = await roleManager.FindByNameAsync(roleName);
cancellationToken.ThrowIfCancellationRequested();
return role == null ? TypedResults.NotFound() : TypedResults.Ok(role);
}).Produces<TRole>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);

routeGroup.MapGet("/", IEnumerable<TRole> (IRoleManager<TRole> roleManager) => {
routeGroup.MapGet("/", IEnumerable<TRole> (IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
cancellationToken.ThrowIfCancellationRequested();
return roleManager.Roles.ToList();
});
}).Produces<IEnumerable<TRole>>(StatusCodes.Status200OK);

return endpoints;
}
Expand All @@ -30,33 +40,45 @@ public static IEndpointRouteBuilder MapRoleManageApi<TRole>(this IEndpointRouteB
where TRole : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapPost("/", async Task<Results<Ok, ValidationProblem>> ([FromBody] TRole role, IRoleManager<TRole> roleManager) => {
var result = await roleManager.CreateAsync(role);
routeGroup.MapPost("/", async Task<IResult> ([FromBody] RoleRequest<TRole> request, IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
if(request?.Role == null)
return ValidationProblemFactory.CreateValidationProblem("InvalidRole", "Role is required.");
cancellationToken.ThrowIfCancellationRequested();
var result = await roleManager.CreateAsync(request.Role);
if(!result.Succeeded)
return result.CreateValidationProblem();
return result.CreatePublicError();

return TypedResults.Ok();
});
}).Produces(StatusCodes.Status200OK)
.ProducesValidationProblem(StatusCodes.Status400BadRequest);

routeGroup.MapPut("/", async Task<Results<Ok, ValidationProblem>> ([FromBody] TRole role, IRoleManager<TRole> roleManager) => {
var result = await roleManager.UpdateAsync(role);
routeGroup.MapPut("/", async Task<IResult> ([FromBody] RoleRequest<TRole> request, IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
if(request?.Role == null)
return ValidationProblemFactory.CreateValidationProblem("InvalidRole", "Role is required.");
cancellationToken.ThrowIfCancellationRequested();
var result = await roleManager.UpdateAsync(request.Role);
if(!result.Succeeded)
return result.CreateValidationProblem();
return result.CreatePublicError();

return TypedResults.Ok();
});
}).Produces(StatusCodes.Status200OK)
.ProducesValidationProblem(StatusCodes.Status400BadRequest);

routeGroup.MapDelete("{roleId}", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string roleId, IRoleManager<TRole> roleManager) => {
routeGroup.MapDelete("{roleId}", async Task<IResult> ([FromRoute] string roleId, IRoleManager<TRole> roleManager, CancellationToken cancellationToken) => {
cancellationToken.ThrowIfCancellationRequested();
var role = await roleManager.FindByIdAsync(roleId);
if(role == null)
return ValidationProblemFactory.CreateValidationProblem("NotFound", "Role Not Found");
return TypedResults.NotFound();

cancellationToken.ThrowIfCancellationRequested();
var result = await roleManager.DeleteAsync(role);
if(!result.Succeeded)
return result.CreateValidationProblem();
return result.CreatePublicError();

return TypedResults.Ok();
});
}).Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound)
.ProducesValidationProblem(StatusCodes.Status400BadRequest);

return endpoints;
}
Expand Down
Loading
Loading