OpenIddict外部登录回调未重定向至授权端点问题
问题解决:OpenIddict外部登录回调未重定向到授权端点
你的代码中Results.SignIn的RedirectUri被忽略、返回200 OK而非302重定向,核心原因是最小API的Results.SignIn不会自动触发认证中间件的重定向逻辑,可通过以下两种方式修复:
方案1:使用HttpContext.SignInAsync替代Results.SignIn
直接调用context.SignInAsync触发认证中间件流程,它会自动处理AuthenticationProperties中的RedirectUri并发送重定向响应:
app.MapMethods("callback/login/github", new[] { HttpMethods.Get, HttpMethods.Post }, async (HttpContext context) => { var result = await context.AuthenticateAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme); var identity = new ClaimsIdentity(authenticationType: "ExternalLogin"); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, result.Principal!.FindFirst("id")!.Value)); var properties = new AuthenticationProperties { RedirectUri = result.Properties!.RedirectUri }; // 触发认证中间件处理重定向逻辑 await context.SignInAsync(new ClaimsPrincipal(identity), properties); return Results.Ok(); });
方案2:为Results.SignIn指定认证方案
若坚持使用Results.SignIn,需明确指定Cookie认证方案(确保关联到处理重定向的中间件):
app.MapMethods("callback/login/github", new[] { HttpMethods.Get, HttpMethods.Post }, async (HttpContext context) => { var result = await context.AuthenticateAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme); var identity = new ClaimsIdentity(authenticationType: "ExternalLogin"); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, result.Principal!.FindFirst("id")!.Value)); var properties = new AuthenticationProperties { RedirectUri = result.Properties!.RedirectUri }; // 指定Cookie认证方案以触发重定向 return Results.SignIn(new ClaimsPrincipal(identity), properties, CookieAuthenticationDefaults.AuthenticationScheme); });
额外注意事项
- 确认
result.Properties.RedirectUri指向正确的OpenIddict授权回调端点(如/connect/authorize/callback),无效地址会导致重定向失效。 - 外部登录生成的
ClaimsIdentity需包含OpenIddict流程所需的必要声明(如NameIdentifier),否则后续授权流程可能出错。
内容的提问来源于stack exchange,提问作者Steve P
相关产品推荐
相关产品推荐

