mirror of
https://github.com/azaion/admin.git
synced 2026-06-21 17:11:09 +00:00
1e1ded73f5
Add RFC 6238 TOTP enrollment, two-step /login flow, recovery codes, and
the amr=["pwd","mfa"] claim that propagates through refresh-token rotation.
- New endpoints: /users/me/mfa/{enroll,confirm,disable} and /login/mfa.
- /login short-circuits to a 5-min ES256 step-1 token (audience-pinned
azaion-mfa-step2) when the user has MFA enabled; real access+refresh
pair is minted only after /login/mfa.
- mfa_secret encrypted at rest via ASP.NET Core IDataProtector
(purpose=Azaion.Mfa.Secret.v1; key folder configurable via
DataProtection:KeysFolder for production persistence).
- Recovery codes (10 single-use, base32, ~80-bit entropy) hashed with
SHA-256 and stored as JSONB; constant-time compare on lookup.
- RFC 6238 §5.2 replay defense via mfa_last_used_window per user.
- Sessions carry mfa_authenticated so /token/refresh re-stamps the
amr claim correctly across the entire 30-day refresh window.
- New audit events: enroll, confirm, disable, login-success/failed,
recovery-used.
- Schema: env/db/10_users_mfa.sql adds users.mfa_* columns and
sessions.mfa_authenticated; mfa_recovery_codes mapped as BinaryJson
in AzaionDbSchemaHolder; disable path uses raw parameterised SQL to
avoid LinqToDB null-literal type-inference on jsonb columns.
E2E: 6 new tests in MfaLoginTests cover all six AC; full suite
82 passed / 0 failed / 3 intentional skips.
Co-authored-by: Cursor <cursoragent@cursor.com>
82 lines
3.1 KiB
C#
82 lines
3.1 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using Azaion.Common.Configs;
|
|
using Azaion.Common.Entities;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Azaion.Services;
|
|
|
|
public interface IAuthService
|
|
{
|
|
Task<User?> GetCurrentUser();
|
|
|
|
/// <summary>
|
|
/// AZ-531 / AZ-532 — mint a 15-minute ES256 access token. <paramref name="sessionId"/>
|
|
/// is stamped as the <c>sid</c> claim (logout / family-revocation key in AZ-535)
|
|
/// and <paramref name="jti"/> is the per-token unique id (AZ-535 access denylist).
|
|
/// AZ-534 — <paramref name="amr"/> values are stamped as repeated <c>amr</c>
|
|
/// claims so verifiers can require step-up MFA. Defaults to <c>["pwd"]</c>.
|
|
/// </summary>
|
|
AccessToken CreateToken(User user, Guid sessionId, Guid jti, IEnumerable<string>? amr = null);
|
|
}
|
|
|
|
public sealed record AccessToken(string Jwt, DateTime ExpiresAt);
|
|
|
|
public class AuthService(
|
|
IHttpContextAccessor httpContextAccessor,
|
|
IOptions<JwtConfig> jwtConfig,
|
|
IJwtSigningKeyProvider signingKeys,
|
|
IUserService userService) : IAuthService
|
|
{
|
|
private readonly JwtConfig _jwt = jwtConfig.Value;
|
|
|
|
private string? GetCurrentUserEmail()
|
|
{
|
|
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
|
return claims?[ClaimTypes.Name].Value;
|
|
}
|
|
|
|
public async Task<User?> GetCurrentUser()
|
|
{
|
|
var email = GetCurrentUserEmail();
|
|
return await userService.GetByEmail(email);
|
|
}
|
|
|
|
public AccessToken CreateToken(User user, Guid sessionId, Guid jti, IEnumerable<string>? amr = null)
|
|
{
|
|
var active = signingKeys.Active;
|
|
var signingCredentials = new SigningCredentials(active.SecurityKey, SecurityAlgorithms.EcdsaSha256);
|
|
|
|
var expires = DateTime.UtcNow.AddMinutes(_jwt.AccessTokenLifetimeMinutes);
|
|
var claims = new List<Claim>
|
|
{
|
|
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new(ClaimTypes.Name, user.Email),
|
|
new(ClaimTypes.Role, user.Role.ToString()),
|
|
new(JwtRegisteredClaimNames.Sid, sessionId.ToString()),
|
|
new(JwtRegisteredClaimNames.Jti, jti.ToString())
|
|
};
|
|
|
|
// AZ-534 — stamp authentication-methods-reference per RFC 8176. Multi-valued:
|
|
// password+TOTP login produces ["pwd","mfa"]; recovery-code login adds "recovery".
|
|
var amrValues = amr?.ToArray() ?? ["pwd"];
|
|
foreach (var v in amrValues)
|
|
claims.Add(new Claim("amr", v));
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(claims),
|
|
Expires = expires,
|
|
Issuer = _jwt.Issuer,
|
|
Audience = _jwt.Audience,
|
|
SigningCredentials = signingCredentials
|
|
};
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
return new AccessToken(tokenHandler.WriteToken(token), expires);
|
|
}
|
|
}
|