从没有承载前缀的授权标头中获取访问令牌

Que*_*n3r 6 c# adal .net-core

我正在为我的 .NET Core 项目使用Microsoft.AspNetCore.Authentication.JwtBearerSystem.IdentityModel.Tokens.Jwt包。

有一些受[Authorize]注释保护的控制器端点必须从请求中获取访问令牌。目前我正在以这种方式在我的控制器方法中获取访问令牌:

string accessTokenWithBearerPrefix = Request.Headers[HeaderNames.Authorization];
string accessTokenWithoutBearerPrefix = accessTokenWithBearerPrefix.Substring("Bearer ".Length);
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的“即用型”解决方案,因为使用上面的代码在从承载令牌中获取子字符串时可能仍然会导致错误。

And*_*ndy 17

这是一种无需进入标题字典即可获取标题的巧妙方法。这也将使框架解析令牌,这就是我相信您正在寻找的:

[HttpGet, Route("someEndpoint")]
public IActionResult SomeEndpoint([FromHeader] string authorization)
{

    if(AuthenticationHeaderValue.TryParse(authorization, out var headerValue))
    {
        // we have a valid AuthenticationHeaderValue that has the following details:

        var scheme = headerValue.Scheme;
        var parameter = headerValue.Parameter;

        // scheme will be "Bearer"
        // parmameter will be the token itself.
    }

    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

您还可以以老式的方式获取标题:

[HttpGet, Route("someEndpoint")]
public IActionResult SomeEndpoint()
{
    var authorization = Request.Headers[HeaderNames.Authorization];

    if (AuthenticationHeaderValue.TryParse(authorization, out var headerValue))
    {
        // we have a valid AuthenticationHeaderValue that has the following details:

        var scheme = headerValue.Scheme;
        var parameter = headerValue.Parameter;

        // scheme will be "Bearer"
        // parmameter will be the token itself.
    }

    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

好的是AuthenticationHeaderValue.TryParse将涵盖奇怪的情况,例如方案和令牌之间是否有不止一次空格,或者方案之前是否有空格,或令牌之后是否有空格......并为您修剪它。

现在,这些情况不应该发生,但是……它们可能会发生,并且 的执行accessTokenWithBearerPrefix.Substring("Bearer ".Length);会失败。这就是为什么我相信您想要一种更具体的方式来解析令牌。


Kah*_*azi 8

您可以将Startup.cs中的 SaveToken 设置为true

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        // your other config
        options.SaveToken = true;
    });
Run Code Online (Sandbox Code Playgroud)

HttpContext并从with方法获取访问令牌GetTokenAsync

using Microsoft.AspNetCore.Authentication;

public class SampleController : Controller
{
    public void Index()
    {
        var accessToken = HttpContext.GetTokenAsync("access_token");
    }
}
Run Code Online (Sandbox Code Playgroud)