【问题标题】:.Net Core JWT generation does not seem to work, what am I doing wrong?.Net Core JWT 生成似乎不起作用,我做错了什么?
【发布时间】:2018-03-29 15:40:12
【问题描述】:

我正在尝试使用System.IdentityModel.Tokens.Jwt 和以下代码生成 Json Web 令牌 (JWT):

public static string GenerateToken()
{
    var now = DateTime.UtcNow;
    var key = Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS");
    var securityKey = new SymmetricSecurityKey(key);

    var claims = new[]
    {
        new Claim("user_id", "John Doe"),
        new Claim("name", "some-guid-will-go-here"),
        new Claim("admin", "true", ClaimValueTypes.Boolean)
    };

    var jwt = new JwtSecurityTokenHandler().CreateJwtSecurityToken(
        issuer: "example.com",
        audience: "example.com",
        subject: new ClaimsIdentity(claims),
        expires: now.AddMinutes(30),
        notBefore: now,
        issuedAt: now,
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256),
        encryptingCredentials: new EncryptingCredentials(securityKey, JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512)
        );

    var token = new JwtSecurityTokenHandler().WriteToken(jwt);

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

当我运行函数 GenerateToken() 时,它会返回一个如下所示的令牌:

eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwidHlwIjoiSldUIn0..EYFD_3JkBLjHFUPfFul-HQ.GP6QX0DAT7xb8rcvAH-1gKVKx2pUpMldHq4UkRevpPF8G7uzlcbMQQtkvavCIfrQ339bOxqBu9Sk9OOnMfq4xcsLs2v9qrlUKM7virT9wf4PcrnywO15xCQcdEFcN2ED4dbmn8mFJpE7jguvIuPHoZM6sYcjvwQS5Xl6vWBFVOFanF0EXauGOhVwmfcU5lCn4Y2cRjM7qD5WY5BuItvlsUEFcYQJsHOfupgdth-cTkTiihUU92R1lQla81WiXyGmS1hJZ4NJk87HUnBYQKBH9JHgJ-_F3x2seQkgCPLTCJmU7YFU_JR8mjlcu97Tl-BHWxn-z1EOpqPTCK1yPXZ6mYXrTy1ber0f8yd1hao9dvbwL3-u689YL3LnntNIV89L1jr0V-emvkTO2GE8k6z-YQ.kzjDt0foAswdWqTsEOPW4e8QbP4XOoKrmxJX0hBozlc

当我尝试使用 jwt.io 验证该令牌时,它不起作用。我无法从令牌中获取有效负载,也无法使用密钥来验证或解密令牌。 我做错了什么或者为什么它不起作用?我错过了什么?

【问题讨论】:

  • 您作为示例提供的 jwt 的 .s 太多。具体来说,在..EYFD,它应该只是一个.。实际上还有一个额外的. 在那里——应该只有 2 个,但你有 4 个。
  • 这很奇怪,我用上面的代码生成的所有标记都得到了 4 个.,我又生成了几个,所有这些标记都连续得到 2 个,后面的字符串中又多了 2 个。为什么会这样?
  • 为你多看一点,额外的.s 等都很好 - 这是因为令牌是加密的。我不认为jwt.io 支持加密的 JWT。我已经设法解密了您在 C# 中的代码生成的令牌,证明该令牌确实有效。

标签: asp.net-core .net-core jwt asp.net-core-webapi json-web-token


【解决方案1】:

将以下行添加到您的ConfigureServices(IServiceCollection services) 中的Startup.cs

services.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = (string)Configuration.GetSection("JwtToken").GetValue(typeof(string), "Issuer"),
        ValidAudience = (string)Configuration.GetSection("JwtToken").GetValue(typeof(string), "Audience"),
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS")),
        TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS")),
        ClockSkew = TimeSpan.FromMinutes(0),
    };
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2012-07-30
    • 2010-11-26
    • 1970-01-01
    • 2015-09-15
    • 2020-07-05
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多