我有一个 Web 应用程序,它使用隐式客户端向 Identity Server 4 验证用户身份。我需要此用户的访问 token ,以便我可以调用另一个 API。
要清楚:
- 我有一个身份服务器。使用身份服务器 4 创建。
- 我在 Asp .net core mvc 中创建了有问题的网络应用程序。
- 在 .net 核心中创建的 API。
Web 应用程序根据身份服务器对用户进行身份验证。一旦他们通过身份验证,我们就使用不记名 token 来访问 API。
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = Configuration["ServiceSettings:IdentityServerEndpoint"];
options.ClientId = "f91ece52-81cf-4b7b-a296-26356f50841f";
options.SignInScheme = "cookie";
});
用户身份验证正常,我可以访问下面的 Controller 。我需要此用户的访问 token ,以便我可以向另一个 API 发出请求。
[Authorize]
public async Task<IActionResult> Index(int clientId, string error)
{
ViewData["Title"] = "Secrets";
if (User.Identity.IsAuthenticated)
{
// All of the below attempts result in either null or empty array
var attempt1 = Request.Headers["Authorization"];
var attempt2 = await HttpContext.GetTokenAsync("access_token");
var attempt3 = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
var attempt4 = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
}
return View();
}
下面确实包含一个名为 cookie 的 header 。有没有办法从中获取访问 token ?
var h = _httpContextAccessor.HttpContext.Request.Headers.ToList();
我如何找到当前经过身份验证的用户的访问 token ?使用隐式登录。
关于混合登录与隐式登录的注意事项:由于此处发布的问题,我无法使用混合登录 Authentication limit extensive header size由于我无法找到该问题的解决方案,建议切换到隐式登录而不是混合登录。隐式似乎并没有创造出混合体所做的巨大 cooking 。
我一直在关注这个来创建隐式客户端 Getting started with Identityserver 4
最佳答案
默认情况下,OpenID Connect 中间件 only requests an identity token (id_token
的 response_type
)。
您需要先使用以下内容更新您的 OpenIdConnectOptions
:
options.ResponseType = "id_token token";
然后您可以使用以下方法将 token 保存到您的 cookie 中:
options.SaveTokens = true;
最后,您可以使用以下方式访问 token :
await HttpContext.GetTokenAsync("access_token");
请注意,在使用隐式流程时,您还需要在 IdentityServer 客户端配置中设置 AllowAccessTokensViaBrowser
标志。
关于c# - 用户已通过身份验证,但访问 token 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50566323/