You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenIddict实现PKCE授权码流:预期返回AccessToken却重定向

问题:OpenIddict实现PKCE授权码流时未输出AccessToken而是触发重定向

基本流程

  • 用户发起认证请求
  • 服务器发送挑战字符串
  • 用户对挑战签名后提交至服务器
  • 服务器验证挑战并完成用户认证

预期与实际行为

  • 预期行为:输出AccessToken
  • 实际行为:系统尝试重定向至重定向URL

启动代码

.AddCookie(AuthConstants.ConsumerAppBiometricAuthenticationScheme, config =>
{
    config.Cookie.HttpOnly = true;
    //options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    config.Cookie.SameSite = SameSiteMode.Lax;
    config.Cookie.Name = AuthConstants.ConsumerAppBiometricAuthenticationScheme;
    config.LoginPath = new PathString("/api/BiometricAuthentication/BiometricChallenge");
    config.ExpireTimeSpan = TimeSpan.FromMinutes(Clients.DefaultAccessTokenLifeTime);
    config.SlidingExpiration = true;
})

授权端点代码

var authScheme = AuthConstants.ConsumerAppBiometricAuthenticationScheme;
var result = await HttpContext.AuthenticateAsync(authScheme);
if (!result.Succeeded)
    return Challenge(authScheme!);
var phone = result.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.MobilePhone);

var claimsPrincipal = await _authorizationService.GrantAuthorizationCode(new AuthorizationCodeCommand
{
    ClientId = request.ClientId,
    Scopes = ImmutableArray<string>.Empty,
    UserName = phone.Value,
    Audiences = request.Audiences
});

// Signing in with the OpenIddict authentication scheme trigger OpenIddict to issue a code (which can be exchanged for an access token)
return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

认证相关代码

[HttpGet]
public async Task<BiometricChallengeView> BiometricChallenge(string returnUrl)
{
    var query = Helper.GetQueryParams(HttpContext.Request.Host.ToString(), returnUrl);
    var phoneNumber = query.Get(AuthConstants.PhoneNumber);
    var challenge = await _authenticationService.GetChallenge(phoneNumber);
    return new BiometricChallengeView
    {
        ReturnUrl = returnUrl,
        UserName = phoneNumber,
        Challenge = challenge
    };

}

[HttpPost]
public async Task<IActionResult> BiometricChallenge(BiometricChallengeView encryptedChallenge)
{
    await _authenticationService.VerifyChallenge(encryptedChallenge.UserName, encryptedChallenge.Challenge);
    await SignInAsync(encryptedChallenge.UserName);
    return Redirect(encryptedChallenge.ReturnUrl);
}

private async Task SignInAsync(string phone)
{
    const string scheme = AuthConstants.ConsumerAppBiometricAuthenticationScheme;
    var claims = new List<Claim>
    {
        new(ClaimTypes.MobilePhone, phone),
        new(ClaimTypes.PrimarySid, Guid.NewGuid().ToString())
    };
    var claimsIdentity = new ClaimsIdentity(claims, scheme);

    await HttpContext.SignInAsync(scheme, new ClaimsPrincipal(claimsIdentity));
}

内容的提问来源于stack exchange,提问作者rksajib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:33:25