feat: complete passkey authentication
This commit is contained in:
1 parent
b51b1868c0
commit
478a403e57
20 files changed
+12847
-1
No files matched your search
@@ -133,6 +133,15 @@ Sso__Enabled=false
|
||||
# 必须与 Keycloak 客户端的 Valid redirect URI 完全一致。
|
||||
# Sso__CallbackUrl=https://jiaowu.example.edu.cn/signin-keycloak
|
||||
|
||||
# Passkey/WebAuthn(可选)。RP ID 必须是最终访问域名,不含协议和端口;Origin 必须
|
||||
# 与浏览器地址栏中的 HTTPS Origin 完全一致。不要从 Host/X-Forwarded-Host 动态推断。
|
||||
Passkeys__Enabled=false
|
||||
# Passkeys__RelyingPartyId=jiaowu.example.edu.cn
|
||||
# Passkeys__RelyingPartyName=明序校园
|
||||
# Passkeys__Origins__0=https://jiaowu.example.edu.cn
|
||||
Passkeys__ChallengeMinutes=5
|
||||
Passkeys__MaximumCredentialsPerUser=10
|
||||
|
||||
AllowedHosts=jiaowu.example.edu.cn
|
||||
Cors__Origins__0=https://jiaowu.example.edu.cn
|
||||
Cors__Origins__1=capacitor://localhost
|
||||
|
||||
@@ -231,6 +231,19 @@ VAPID 密钥;私钥、SMTP 密码不得写入 `appsettings.json` 或提交到
|
||||
没有逐字段快照时自动反向写入并不安全。需要纠正时应修复源数据后重新预检导入,正式业务
|
||||
的撤销继续使用各模块已有的审核、归档或更正流程。
|
||||
|
||||
### Passkey 登录
|
||||
|
||||
用户可在“个人账户”中通过当前密码确认后添加、命名和撤销 Passkey,并在登录页直接使用
|
||||
设备锁屏、指纹或安全密钥完成无用户名 WebAuthn 登录。新增凭据强制为可发现凭据,登录选项
|
||||
不接收账号名,也不返回账号对应的凭据列表,避免形成账号或 Passkey 枚举接口。挑战只保存
|
||||
令牌哈希,五分钟内有效且通过数据库条件更新保证只能消费一次;私钥始终保留在认证器中。
|
||||
密码、TOTP 与统一身份认证继续作为独立登录和恢复入口。
|
||||
|
||||
生产环境默认关闭 Passkey。启用前必须通过 `Passkeys__RelyingPartyId` 和
|
||||
`Passkeys__Origins__*` 固定配置最终 HTTPS 域名,不能依据请求头动态推断;多域名部署应
|
||||
分别确认 RP ID 的域后缀关系。Capacitor 原生凭据管理器仍属于单独的设备端集成,Web
|
||||
页面构建或浏览器验收不能替代 Android/iOS 真机验收。
|
||||
|
||||
## MySQL 8.4 生产部署
|
||||
|
||||
非 Development 环境只允许使用 MySQL。构建发布包与数据库配置相互独立:
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
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")]
|
||||
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 userManager.CheckPasswordAsync(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}")]
|
||||
public async Task<IActionResult> Delete(
|
||||
Guid id,
|
||||
PasswordConfirmationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await CurrentUserAsync();
|
||||
if (user is null) return Unauthorized();
|
||||
if (!await userManager.CheckPasswordAsync(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);
|
||||
Loaded 3 of 20 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user