从没有持有者前缀的授权 header 中获取访问令牌

Fetch access token from authorization header without bearer prefix

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

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

string accessTokenWithBearerPrefix = Request.Headers[HeaderNames.Authorization];
string accessTokenWithoutBearerPrefix = accessTokenWithBearerPrefix.Substring("Bearer ".Length);

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

您可以使用以下代码获取安全令牌。

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

另外,如果你想,可以参考下面的代码:

public TokenValidationParameters CreateTokenValidationParameters()
{
    var result = new TokenValidationParameters
    {
    ValidateIssuer = false,
    ValidIssuer = ValidIssuer,

    ValidateAudience = false,
    ValidAudience = ValidAudience,

    ValidateIssuerSigningKey = false,
    //IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey)),
    //comment this and add this line to fool the validation logic
    SignatureValidator = delegate(string token, TokenValidationParameters parameters)
    {
        var jwt = new JwtSecurityToken(token);

        return jwt;
    },

    RequireExpirationTime = true,
    ValidateLifetime = true,

    ClockSkew = TimeSpan.Zero,
    };

    result.RequireSignedTokens = false;

    return result;
}

这是一种无需进入 headers 字典即可获取 header 的巧妙方法。这也会让框架解析令牌,这就是我相信你正在寻找的东西:

[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();
}

您还可以通过 old-school 的方式获取 header:

[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();
}

好的是 AuthenticationHeaderValue.TryParse 将涵盖奇怪的情况,例如如果方案和令牌之间存在不止一次 space,或者方案之前有 space,或令牌后 spaces... trim 为您准备。

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

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

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        // your other config
        options.SaveToken = true;
    });

并使用 GetTokenAsync 方法从 HttpContext 获取访问令牌。

using Microsoft.AspNetCore.Authentication;

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