使用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
相关产品推荐
相关产品推荐

