【问题标题】:.Net Core 3.1 Jwt Validate Issuer does not seem to work.Net Core 3.1 Jwt Validate Issuer 似乎不起作用
【发布时间】:2020-04-10 01:40:14
【问题描述】:

使用带有 Jwt 身份验证的 .Net Core 3.1 WebApi 似乎工作正常,除非我们尝试使用 ValidateIssuer 和 Validate Audience。 当我们将这些属性设置为 true 时,我们会得到一个未经授权的 Http 状态代码。 我们从应用设置中获取 Audience 和 Issuer 的值,因此我们知道它们是相同的。 以下是我们的 startup.cs 中的代码:

//
// Configure JWT authentication from the 'jwtIssuerOptions' values in the appsettings.json file
//
Models.JwtIssuerOptions jwtSettings = _appConfiguration.GetSection("jwtIssuerOptions").Get<Models.JwtIssuerOptions>();
var keyBytes = Encoding.UTF8.GetBytes(jwtSettings.JwtSecret);
SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(keyBytes);

services.AddAuthentication(a =>
{
    a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(b =>
    {
        b.RequireHttpsMetadata = false;
        b.SaveToken = true;
        b.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidAudience =  jwtSettings.Audience ,
            ValidIssuer =  jwtSettings.Issuer ,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = symmetricSecurityKey,
            TokenDecryptionKey = symmetricSecurityKey,
            ValidateIssuer = true,
            ValidateAudience = true
        };
    });

以下是我们的 Auth Helper 中创建 Jwt 的代码:

private void CreateTheJWT(EndUserCredentials user)
{            
    var keyBytes = Encoding.UTF8.GetBytes(_jwtIssuerOptions.JwtSecret);
    var symmetricSecurityKey = new SymmetricSecurityKey(keyBytes);
    var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
    var cryptoKey = new EncryptingCredentials(symmetricSecurityKey, JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[] {
            new Claim(ClaimTypes.Name, user.Name),
            new Claim(ClaimTypes.Email, user.Name),
            new Claim("EndUser", System.Text.Json.JsonSerializer.Serialize( user)),
        }),
        Expires = DateTime.UtcNow.AddMinutes(_jwtIssuerOptions.TimeoutMinutes),
        Audience = _jwtIssuerOptions.Issuer,
        Issuer = _jwtIssuerOptions.Audience,
        NotBefore = DateTime.UtcNow.AddMinutes(-2),
        IssuedAt = DateTime.UtcNow.AddMinutes(-1),
        SigningCredentials = signingCredentials,
        EncryptingCredentials = cryptoKey
    };

    foreach (string role in user.Roles)
    {
        tokenDescriptor.Subject.AddClaim(new Claim(ClaimTypes.Role, role));
    }
    var tokenHandler = new JwtSecurityTokenHandler();
    var token = tokenHandler.CreateToken(tokenDescriptor);
    user.Token = tokenHandler.WriteToken(token);
}

当我们将违规属性设置为“false”时,一切正常。任何帮助表示赞赏!

【问题讨论】:

    标签: c# asp.net-core jwt


    【解决方案1】:

    在我看来,您的发行人和听众已经互换了。您可以在 CreateTheJWT 函数中重新分配吗?

    Audience = _jwtIssuerOptions.Audience,
    Issuer = _jwtIssuerOptions.Issuer,
    

    【讨论】:

      【解决方案2】:

      如果您像我一样在这里,并且没有交换您的发行人和受众。

      确保您的 Startup.ConfigureServices 中有此内容。

      app.UseAuthentication();
      app.UseAuthorization();
      

      【讨论】:

        猜你喜欢
        • 2018-03-29
        • 2020-07-05
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-25
        • 1970-01-01
        • 2023-03-02
        相关资源
        最近更新 更多