如何在 Asp.net Core 中手动验证 JWT 签名

Lea*_*rve 2 c# jwt asp.net-core

我有一个没有任何控制器实现的 Asp Net Core API。客户端(Auth0 实现)正在传递一个 JWT 令牌(RS256 alg),我需要验证签名是否有效。我已经浏览了 Auth0 官方文档,建议实现 JwtBearer 并在启动配置中将应用程序设置为 UseAuthentication

Microsoft.AspNetCore.Authentication.JwtBearer

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddMvc();

    // 1. Add Authentication Services
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(options =>
    {
        options.Authority = "https://myapi.auth0.com/";
        options.Audience = "API/Endpoint";
    });
}
Run Code Online (Sandbox Code Playgroud)

如上所述,此 API 中没有控制器,我无法使用 Authorize attrubute 装饰该方法,因此只能选择手动验证此签名。出于这个原因,我已经阅读了堆栈溢出帖子,其中人们提到了不同的方法,例如使用

System.IdentityModel.Tokens.Jwt

而其他人反对它并建议使用低级实现等。我已经尝试了几个但到目前为止没有成功。

假设以下方法是接收 JWT 令牌的 API 的入口点。请有人告诉我我需要做什么才能手动验证签名

    public Task InvokeAsync(HttpContext context)
    {
        var accessToken = context.Request.Headers["Authorization"];
        // Here I wan't to verify the signature?
        // This token has RS256 alg
    }
Run Code Online (Sandbox Code Playgroud)

以下是 JWT 解码结果

在此处输入图片说明

Luc*_*iro 7

你可以这样做:

public Task InvokeAsync(HttpContext context)
{
    var accessToken = context.Request.Headers["Authorization"];
    var secretKey = "Insert your secret key here";

    var validationParameters = new TokenValidationParameters()
    {
        ValidateIssuerSigningKey = true;
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
        // Add any other validations: issuer, audience, lifetime, etc
    }

    var handler = new JwtSecurityTokenHandler();

    var principal = handler.ValidateToken(accessToken, validationParameters, out var validToken);
    JwtSecurityToken validJwt = validToken as JwtSecurityToken;

    if (validJwt == null)
    {
        throw new ArgumentException("Invalid JWT");
    }

    if (!validJwt.Header.Alg.Equals(SecurityAlgorithms.RsaSha256Signature, StringComparison.Ordinal))
    {
        throw new ArgumentException("Algorithm must be RS256");
    }

    // Add any validations which cannot be included into TokenValidationParameters

    // Validation passed, continue with your logic
}
Run Code Online (Sandbox Code Playgroud)

它基于这篇文章,它解释了如何验证通过 cookie 接收到的 jwt 令牌。尽管目标与您的不同,但验证令牌的方式可以应用于您的问题。