简体   繁体   English

使用 ASP.NET Core 的 JWT 令牌无效令牌错误

[英]JWT token invalid token error using ASP.NET Core

I am creating an ASP.NET Core Web API.我正在创建一个 ASP.NET Core Web API。 In this, I am using JWT token for authentication.在此,我使用 JWT 令牌进行身份验证。 I have created a demo SQL database for testing and I am testing my APIs using Fiddler.我创建了一个用于测试的演示 SQL 数据库,并且正在使用 Fiddler 测试我的 API。 My ConfigureServices method of Startup class looks like this:我的Startup类的ConfigureServices方法如下所示:

public void ConfigureServices(IServiceCollection services)
{
    var authPol = new AuthorizationPolicyBuilder()
                                             .AddAuthenticationSchemes(
                                                             new string[] { JwtBearerDefaults.AuthenticationScheme })
                                             .RequireAuthenticatedUser()
                                             .Build();
                          
    services.AddControllers(
                config => 
                {
                    config.Filters.Add(new AuthorizeFilter(authPol));
                }).AddXmlSerializerFormatters()
                .AddXmlDataContractSerializerFormatters();

    services.AddDbContext<BikeStoresContext>();

    // JWT Token
    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this-is-my-jwt-security-key"));

    var tokenValidationParameters = new TokenValidationParameters()
            {
                IssuerSigningKey = signingKey,
                ValidateIssuer = false,
                ValidateAudience = true,
                ClockSkew = TimeSpan.Zero
            };

    services.AddAuthentication(x => x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(jwt =>
                {
                    jwt.TokenValidationParameters = tokenValidationParameters;
                });

    services.AddIdentity<IdentityUser, IdentityRole>()
       .AddEntityFrameworkStores<BikeStoresContext>()
       .AddDefaultTokenProviders();

    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "BikeStoreAPI", Version = "v1" });
            });
}

This is my JWT token generation code from Accounts controller's login action method:这是来自 Accounts 控制器的登录操作方法的 JWT 令牌生成代码:

var user = await userManager.FindByEmailAsync(model.UserEmail);
var roles = await userManager.GetRolesAsync(user);

IdentityOptions identityOptions = new IdentityOptions();
var claims = new Claim[]
                 {
                     new Claim("Lid", "123456789"),
                     new Claim(identityOptions.ClaimsIdentity.UserIdClaimType, user.Id),
                     new Claim(identityOptions.ClaimsIdentity.UserNameClaimType, user.UserName),
                     new Claim(identityOptions.ClaimsIdentity.RoleClaimType, roles[0]),
                     new Claim(identityOptions.ClaimsIdentity.EmailClaimType, user.Email)
                 };

var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this-is-my-jwt-security-key"));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

var jwt = new JwtSecurityToken(claims: claims, 
                    signingCredentials: signingCredentials, 
                    expires: DateTime.Now.AddMinutes(30));

return Ok(new
          {
              userName = model.UserEmail,
              role = roles[0],
              token = new JwtSecurityTokenHandler().WriteToken(jwt)
          });

JWT token is generated, but when I used the JWT token to access other APIs, I am getting this error.生成了 JWT 令牌,但是当我使用 JWT 令牌访问其他 API 时,我收到此错误。

WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'empty' is invalid" WWW-Authenticate: Bearer error="invalid_token", error_description="观众 'empty' 无效"

I don't know where I made mistake in this code.我不知道我在这段代码中哪里出错了。 Is there any change required?是否需要进行任何更改?

Fiddler Screenshot:提琴手截图:

在此处输入图像描述

In the tokenValidationParameters you set ValidateAudience = true , which means that the aud -claim will be checked.tokenValidationParameters设置ValidateAudience = true ,这意味着将检查aud -claim。 But you never set a value for ValidAudience and also don't add an aud -claim to the token.但是您永远不会为ValidAudience设置值,也不会向令牌添加aud -claim。

You can either turn off the check by setting您可以通过设置关闭检查

ValidateAudience = false

or add a ValidAudience like eg:或添加一个ValidAudience ,例如:

ValidAudience = "audience"

and add the aud -claim with:并添加aud -claim :

var jwt = new JwtSecurityToken(claims: claims, 
                audience: "audience",
                signingCredentials: signingCredentials, 
                expires: DateTime.Now.AddMinutes(30));

You can read this Q/A to learn more about the meaning of the aud - claim.您可以阅读此 Q/A以了解有关aud - 声明的含义的更多信息。

Besides the audience, there's also the issuer ( iss -claim), which can be validated in the same way.除了观众,还有发行者( iss -claim),可以用同样的方式进行验证。

In the tokenValidationParameters add/change the settings:tokenValidationParameters添加/更改设置:

ValidateIssuer = true
ValidIssuer = "issuer"

and then pass the issuer to the constructor when you create the token:然后在创建令牌时将颁发者传递给构造函数:

var jwt = new JwtSecurityToken(claims: claims, 
                issuer: "issuer"
                audience: "audience",
                signingCredentials: signingCredentials, 
                expires: DateTime.Now.AddMinutes(30));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM