c# - JwtSecurityTokenHandler 返回小写声明类型

标签 c# asp.net-web-api oauth jwt http-token-authentication

我正在使用 Auth0 和 JWT 对我的应用程序实现身份验证。我所有的声明名称都是大写格式,但是一旦 JwtSecurityTokenHandler 将我的 token 转换为 JwtSecurityToken,所有声明类型都是 JwtSecurityToken 的小写类型。

声明和构建 token

private string BuildToken(UserModel user)
    {
        var claims = new[] {
            new Claim(JwtRegisteredClaimNames.Sub, user.Name),
            new Claim(JwtRegisteredClaimNames.Email, user.Email),
            new Claim(JwtRegisteredClaimNames.Birthdate, user.Birthdate.ToString("yyyy-MM-dd")),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          claims,
          expires: DateTime.Now.AddMinutes(30),
          signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

JwtSecurityTokenHandler

var handler = new JwtSecurityTokenHandler();
var tokenS = handler.ReadToken(context.HttpContext.Request.Headers["Authorization"]) as JwtSecurityToken;
var jti = tokenS.Claims.First(claim => claim.Type == "Sub").Value;  //here Sub is giving exception, but if i change it to lower case sub, working fine.

最佳答案

JWT区分大小写。 sub claim被定义为小写。

JwtRegisteredClaimNames.Sub 一定不能让您认为存在名为 Sub 的声明。这只是您使用的库中的名称,而不是 JWT 中编码的声明名称。

sub 正确,Sub 未定义。

关于c# - JwtSecurityTokenHandler 返回小写声明类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574951/

相关文章:

asp.net-mvc - 使用 MVC、AngularJS 和 Entity Framework 编辑表格行

c# - OAuth with OWIN 如何在 MVC5 中工作?

c# - 事件和委托(delegate)与调用方法

c# - 如何获取文件到WP7?

c# - 来自数据库的数据未返回,但正常列表是

php - Yii OAuth 实现

Java HTTPS (SSL) 连接返回 400 状态,其中 CURL/ARC 适用于相同的 URL

c# - 生成不重复的随机数.C#

c# - 在 C# 中抑制事件的 "is never used"警告

c# - 捕获对 Web Api 2.0 的所有请求,无论是否已映射