用户已通过身份验证,但访问令牌在哪里?

DaI*_*mTo 5 c# asp.net-core-mvc identityserver4

我有一个Web应用程序,它使用隐式客户端向Identity Server 4验证用户身份.我需要此用户的访问令牌,以便我可以调用另一个API.

要明确:

  1. 我有一个身份服务器.使用Identity Server 4创建.
  2. 我在Asp .net core mvc中创建了有问题的Web应用程序.
  3. 在.net核心中创建的API.

Web应用程序根据身份服务器对用户进行身份验证.一旦对它们进行了身份验证,我们就会使用承载令牌来访问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";
            });
Run Code Online (Sandbox Code Playgroud)

用户正在进行身份验证,我可以访问下面的控制器.我需要为此用户提供访问令牌,以便我可以向另一个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();
    }
Run Code Online (Sandbox Code Playgroud)

以下包含名为cookie的标头.有没有办法获取访问令牌?

  var h = _httpContextAccessor.HttpContext.Request.Headers.ToList();
Run Code Online (Sandbox Code Playgroud)

如何为当前经过身份验证的用户找到访问令牌?使用隐式登录.

关于混合与隐式登录的注意事项:由于此处发布的问题,我无法使用混合登录身份验证限制扩展标头大小 由于我无法找到该问题的解决方案,因此建议切换到隐式登录而不是混合登录.隐含似乎并没有创造出混合动力的巨型烹饪.

我一直在关注这个以创建隐式客户端Identityserver 4入门

Sco*_*ady 5

默认情况下,OpenID Connect中间件仅请求身份令牌response_typeid_token)。

您首先需要更新OpenIdConnectOptions以下内容:

options.ResponseType = "id_token token";
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下方法将令牌保存到Cookie中:

options.SaveTokens = true;
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用以下命令访问令牌:

await HttpContext.GetTokenAsync("access_token");
Run Code Online (Sandbox Code Playgroud)

请注意,AllowAccessTokensViaBrowser使用隐式流时,还需要在IdentityServer客户端配置中设置标志。