372 lines
15 KiB
C#
372 lines
15 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using Fido2NetLib;
|
|
using Fido2NetLib.Objects;
|
|
using Jiaowu.Api.Domain.Identity;
|
|
using Jiaowu.Api.Infrastructure.Auth;
|
|
using Jiaowu.Api.Infrastructure.Persistence;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
using Microsoft.AspNetCore.WebUtilities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Jiaowu.Api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/auth/passkeys")]
|
|
public sealed class PasskeyController(
|
|
AppDbContext db,
|
|
UserManager<ApplicationUser> userManager,
|
|
IFido2 fido2,
|
|
IPasskeyCeremonyStore ceremonies,
|
|
IAuthSessionService authSessionService,
|
|
IOptions<PasskeyOptions> options) : ControllerBase
|
|
{
|
|
private readonly PasskeyOptions _options = options.Value;
|
|
|
|
[AllowAnonymous]
|
|
[HttpGet("settings")]
|
|
public ActionResult GetSettings() => Ok(new
|
|
{
|
|
_options.Enabled,
|
|
RelyingPartyName = _options.Enabled ? _options.RelyingPartyName : null
|
|
});
|
|
|
|
[Authorize]
|
|
[HttpGet]
|
|
public async Task<ActionResult> GetCredentials(CancellationToken cancellationToken)
|
|
{
|
|
var userId = CurrentUserId();
|
|
if (userId is null) return Unauthorized();
|
|
var items = await db.PasskeyCredentials.AsNoTracking()
|
|
.Where(x => x.UserId == userId)
|
|
.OrderByDescending(x => x.LastUsedAt ?? x.CreatedAt)
|
|
.Select(x => new
|
|
{
|
|
x.Id,
|
|
x.FriendlyName,
|
|
x.Transports,
|
|
x.IsBackupEligible,
|
|
x.IsBackedUp,
|
|
x.CreatedAt,
|
|
x.LastUsedAt
|
|
})
|
|
.ToListAsync(cancellationToken);
|
|
return Ok(new { Enabled = _options.Enabled, Items = items });
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPost("registration/options")]
|
|
[EnableRateLimiting("sensitive-auth")]
|
|
public async Task<ActionResult> RegistrationOptions(
|
|
PasskeyRegistrationOptionsRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!_options.Enabled) return PasskeysDisabled();
|
|
var user = await CurrentUserAsync();
|
|
if (user is null) return Unauthorized();
|
|
if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword))
|
|
return Unauthorized(PasswordProblem());
|
|
var credentials = await db.PasskeyCredentials.AsNoTracking()
|
|
.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);
|
|
if (credentials.Count >= _options.MaximumCredentialsPerUser)
|
|
return Conflict(new ProblemDetails
|
|
{
|
|
Title = "Passkey 数量已达上限",
|
|
Detail = $"每个账号最多保存 {_options.MaximumCredentialsPerUser} 个 Passkey。",
|
|
Status = StatusCodes.Status409Conflict
|
|
});
|
|
|
|
var fidoUser = new Fido2User
|
|
{
|
|
Id = user.Id.ToByteArray(),
|
|
Name = user.UserName ?? user.Id.ToString("D"),
|
|
DisplayName = user.DisplayName
|
|
};
|
|
var createOptions = fido2.RequestNewCredential(new RequestNewCredentialParams
|
|
{
|
|
User = fidoUser,
|
|
ExcludeCredentials = credentials.Select(x =>
|
|
new PublicKeyCredentialDescriptor(
|
|
WebEncoders.Base64UrlDecode(x.CredentialId)))
|
|
.ToArray(),
|
|
AuthenticatorSelection = new AuthenticatorSelection
|
|
{
|
|
ResidentKey = ResidentKeyRequirement.Required,
|
|
UserVerification = UserVerificationRequirement.Required
|
|
},
|
|
AttestationPreference = AttestationConveyancePreference.None,
|
|
Extensions = new AuthenticationExtensionsClientInputs
|
|
{
|
|
CredProps = true
|
|
}
|
|
});
|
|
var ceremonyId = await ceremonies.CreateAsync(new PasskeyCeremony(
|
|
PasskeyCeremonyKind.Registration,
|
|
user.Id,
|
|
false,
|
|
request.FriendlyName.Trim(),
|
|
createOptions.ToJson()), cancellationToken);
|
|
return Ok(new { CeremonyId = ceremonyId, Options = createOptions });
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPost("registration/complete")]
|
|
public async Task<ActionResult> CompleteRegistration(
|
|
PasskeyRegistrationCompleteRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!_options.Enabled) return PasskeysDisabled();
|
|
var userId = CurrentUserId();
|
|
var ceremony = await ceremonies.TakeAsync(request.CeremonyId, cancellationToken);
|
|
if (userId is null || ceremony is not
|
|
{
|
|
Kind: PasskeyCeremonyKind.Registration,
|
|
UserId: not null
|
|
} || ceremony.UserId != userId)
|
|
return InvalidCeremony();
|
|
|
|
try
|
|
{
|
|
var result = await fido2.MakeNewCredentialAsync(new MakeNewCredentialParams
|
|
{
|
|
AttestationResponse = request.Credential,
|
|
OriginalOptions = CredentialCreateOptions.FromJson(ceremony.OptionsJson),
|
|
IsCredentialIdUniqueToUserCallback = async (args, token) =>
|
|
!await db.PasskeyCredentials.AsNoTracking().AnyAsync(
|
|
x => x.CredentialIdHash == Hash(args.CredentialId), token)
|
|
}, cancellationToken);
|
|
var credential = new PasskeyCredential
|
|
{
|
|
UserId = userId.Value,
|
|
CredentialId = WebEncoders.Base64UrlEncode(result.Id),
|
|
CredentialIdHash = Hash(result.Id),
|
|
PublicKey = result.PublicKey,
|
|
SignatureCounter = result.SignCount,
|
|
FriendlyName = ceremony.FriendlyName ?? "Passkey",
|
|
Transports = result.Transports.Length == 0
|
|
? null
|
|
: string.Join(',', result.Transports.Select(x => x.ToString())),
|
|
IsBackupEligible = result.IsBackupEligible,
|
|
IsBackedUp = result.IsBackedUp
|
|
};
|
|
db.PasskeyCredentials.Add(credential);
|
|
await db.SaveChangesAsync(cancellationToken);
|
|
return Ok(new { credential.Id, credential.FriendlyName });
|
|
}
|
|
catch (Fido2VerificationException)
|
|
{
|
|
return InvalidCredential();
|
|
}
|
|
catch (DbUpdateException)
|
|
{
|
|
return Conflict(new ProblemDetails
|
|
{
|
|
Title = "Passkey 已存在",
|
|
Detail = "该 Passkey 已经绑定到平台账号。",
|
|
Status = StatusCodes.Status409Conflict
|
|
});
|
|
}
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[EnableRateLimiting("public-auth")]
|
|
[HttpPost("login/options")]
|
|
public async Task<ActionResult> LoginOptions(
|
|
PasskeyLoginOptionsRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!_options.Enabled) return PasskeysDisabled();
|
|
var assertionOptions = fido2.GetAssertionOptions(new GetAssertionOptionsParams
|
|
{
|
|
AllowedCredentials = [],
|
|
UserVerification = UserVerificationRequirement.Required
|
|
});
|
|
var ceremonyId = await ceremonies.CreateAsync(new PasskeyCeremony(
|
|
PasskeyCeremonyKind.Authentication,
|
|
null,
|
|
request.IsNativeApp,
|
|
null,
|
|
assertionOptions.ToJson()), cancellationToken);
|
|
return Ok(new { CeremonyId = ceremonyId, Options = assertionOptions });
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[EnableRateLimiting("public-auth")]
|
|
[HttpPost("login/complete")]
|
|
public async Task<ActionResult<LoginResponse>> CompleteLogin(
|
|
PasskeyLoginCompleteRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!_options.Enabled) return PasskeysDisabled();
|
|
var ceremony = await ceremonies.TakeAsync(request.CeremonyId, cancellationToken);
|
|
if (ceremony is not { Kind: PasskeyCeremonyKind.Authentication })
|
|
return InvalidCeremony();
|
|
if (request.Credential.RawId is not { Length: > 0 })
|
|
return InvalidCredential();
|
|
var hash = Hash(request.Credential.RawId);
|
|
var credential = await db.PasskeyCredentials.Include(x => x.User)
|
|
.SingleOrDefaultAsync(x => x.CredentialIdHash == hash, cancellationToken);
|
|
var user = credential?.User;
|
|
if (credential is null || user is null || !user.IsEnabled ||
|
|
(ceremony.UserId.HasValue && ceremony.UserId != user.Id) ||
|
|
await userManager.IsLockedOutAsync(user))
|
|
return Unauthorized(LoginProblem());
|
|
|
|
try
|
|
{
|
|
var result = await fido2.MakeAssertionAsync(new MakeAssertionParams
|
|
{
|
|
AssertionResponse = request.Credential,
|
|
OriginalOptions = AssertionOptions.FromJson(ceremony.OptionsJson),
|
|
StoredPublicKey = credential.PublicKey,
|
|
StoredSignatureCounter = credential.SignatureCounter,
|
|
IsUserHandleOwnerOfCredentialIdCallback = (args, _) =>
|
|
Task.FromResult(
|
|
args.CredentialId.SequenceEqual(
|
|
WebEncoders.Base64UrlDecode(credential.CredentialId)) &&
|
|
args.UserHandle is { Length: > 0 } &&
|
|
args.UserHandle.SequenceEqual(user.Id.ToByteArray()))
|
|
}, cancellationToken);
|
|
var now = DateTime.UtcNow;
|
|
await db.PasskeyCredentials.Where(x => x.Id == credential.Id)
|
|
.ExecuteUpdateAsync(setters => setters
|
|
.SetProperty(x => x.SignatureCounter,
|
|
x => x.SignatureCounter < result.SignCount
|
|
? result.SignCount
|
|
: x.SignatureCounter)
|
|
.SetProperty(x => x.IsBackedUp, result.IsBackedUp)
|
|
.SetProperty(x => x.LastUsedAt, now), cancellationToken);
|
|
await userManager.ResetAccessFailedCountAsync(user);
|
|
user.LastLoginAt = now;
|
|
await db.SaveChangesAsync(cancellationToken);
|
|
var roles = await userManager.GetRolesAsync(user);
|
|
var session = await authSessionService.CreateAsync(
|
|
user,
|
|
roles,
|
|
ceremony.IsNativeApp
|
|
? AuthenticationClientType.App
|
|
: AuthenticationClientType.Web,
|
|
cancellationToken);
|
|
return await AuthController.CreateLoginResponseAsync(
|
|
db, session, cancellationToken);
|
|
}
|
|
catch (Fido2VerificationException)
|
|
{
|
|
return Unauthorized(LoginProblem());
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPut("{id:guid}")]
|
|
public async Task<IActionResult> Rename(
|
|
Guid id,
|
|
RenamePasskeyRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var userId = CurrentUserId();
|
|
var credential = await db.PasskeyCredentials.SingleOrDefaultAsync(
|
|
x => x.Id == id && x.UserId == userId, cancellationToken);
|
|
if (credential is null) return NotFound();
|
|
credential.FriendlyName = request.FriendlyName.Trim();
|
|
await db.SaveChangesAsync(cancellationToken);
|
|
return NoContent();
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpDelete("{id:guid}")]
|
|
[EnableRateLimiting("sensitive-auth")]
|
|
public async Task<IActionResult> Delete(
|
|
Guid id,
|
|
PasswordConfirmationRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var user = await CurrentUserAsync();
|
|
if (user is null) return Unauthorized();
|
|
if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword))
|
|
return Unauthorized(PasswordProblem());
|
|
var credential = await db.PasskeyCredentials.SingleOrDefaultAsync(
|
|
x => x.Id == id && x.UserId == user.Id, cancellationToken);
|
|
if (credential is null) return NotFound();
|
|
db.PasskeyCredentials.Remove(credential);
|
|
await db.SaveChangesAsync(cancellationToken);
|
|
return NoContent();
|
|
}
|
|
|
|
private Guid? CurrentUserId()
|
|
{
|
|
var value = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
return Guid.TryParse(value, out var id) ? id : null;
|
|
}
|
|
|
|
private async Task<ApplicationUser?> CurrentUserAsync()
|
|
{
|
|
var id = CurrentUserId();
|
|
return id.HasValue
|
|
? await userManager.FindByIdAsync(id.Value.ToString("D"))
|
|
: null;
|
|
}
|
|
|
|
private static string Hash(byte[] credentialId) =>
|
|
Convert.ToHexString(SHA256.HashData(credentialId)).ToLowerInvariant();
|
|
|
|
private ObjectResult PasskeysDisabled() => StatusCode(
|
|
StatusCodes.Status503ServiceUnavailable,
|
|
new ProblemDetails
|
|
{
|
|
Title = "Passkey 未启用",
|
|
Detail = "管理员尚未为当前站点配置 Passkey 的 RP ID 与安全 Origin。",
|
|
Status = StatusCodes.Status503ServiceUnavailable
|
|
});
|
|
|
|
private ActionResult InvalidCeremony() => BadRequest(new ProblemDetails
|
|
{
|
|
Title = "Passkey 请求已失效",
|
|
Detail = "本次 Passkey 请求已过期、已使用或不属于当前账号,请重新开始。",
|
|
Status = StatusCodes.Status400BadRequest
|
|
});
|
|
|
|
private ActionResult InvalidCredential() => BadRequest(new ProblemDetails
|
|
{
|
|
Title = "Passkey 验证失败",
|
|
Detail = "浏览器返回的 Passkey 凭据无效,请重新尝试。",
|
|
Status = StatusCodes.Status400BadRequest
|
|
});
|
|
|
|
private static ProblemDetails PasswordProblem() => new()
|
|
{
|
|
Title = "验证失败",
|
|
Detail = "当前密码不正确。",
|
|
Status = StatusCodes.Status401Unauthorized
|
|
};
|
|
|
|
private static ProblemDetails LoginProblem() => new()
|
|
{
|
|
Title = "登录失败",
|
|
Detail = "Passkey 无效、已过期或账号已停用。",
|
|
Status = StatusCodes.Status401Unauthorized
|
|
};
|
|
}
|
|
|
|
public sealed record PasskeyRegistrationOptionsRequest(
|
|
[Required, MaxLength(100)] string CurrentPassword,
|
|
[Required, MinLength(1), MaxLength(100)] string FriendlyName);
|
|
|
|
public sealed record PasskeyRegistrationCompleteRequest(
|
|
[Required, MaxLength(100)] string CeremonyId,
|
|
[Required] AuthenticatorAttestationRawResponse Credential);
|
|
|
|
public sealed record PasskeyLoginOptionsRequest(
|
|
bool IsNativeApp = false);
|
|
|
|
public sealed record PasskeyLoginCompleteRequest(
|
|
[Required, MaxLength(100)] string CeremonyId,
|
|
[Required] AuthenticatorAssertionRawResponse Credential);
|
|
|
|
public sealed record RenamePasskeyRequest(
|
|
[Required, MinLength(1), MaxLength(100)] string FriendlyName);
|