【问题标题】:JWT token not being validated correctlyJWT 令牌未正确验证
【发布时间】:2020-05-18 22:30:24
【问题描述】:

我有一个使用 JWT 进行验证的 ASP.NET Core MVC 应用程序

我在启动类中添加了身份验证,使用我们的 appsettings 文件中的令牌密码来验证令牌。

services.Configure<ApplicationSettings>(Configuration.GetSection("AppSettings"));

var key = System.Text.Encoding.UTF8
            .GetBytes(Configuration.GetSection("AppSettings:Token").Value);

services.AddAuthentication(x => {
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x => {
    x.RequireHttpsMetadata = false;
    x.SaveToken = false;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false,
        ClockSkew =  TimeSpan.Zero
    };
});

并添加授权中间件

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors("MyPolicy");

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

现在,当用户尝试登录时,将运行以下控制器方法,使用相同的令牌密钥生成令牌。

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
    {
        var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

        var result = await _signInManager
            .CheckPasswordSignInAsync(user, userForLoginDto.Password, false);



        if (result.Succeeded)
        {
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("UserID",user.Id.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8
                    .GetBytes(appSettings.Token)), SecurityAlgorithms.HmacSha256Signature)
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.WriteToken(securityToken);

            return Ok(new { token });
        }

        return Unauthorized();
    }

所以当用户登录时,会生成一个令牌并发回给客户端。

此时我希望我可以将[Authorize] 属性添加到控制器方法,然后MVC 框架将在http 标头中查找有效令牌。所以我创建了一个测试控制器方法

[HttpGet]
[Authorize]
public IActionResult Get()
{
    return Ok("Test");
}

并发送一个与测试控制器方法相对应的请求,其中 Authorization 标头设置为Bearer &lt;Token&gt;,但我仍然得到未经授权的 401。

谁能解释为什么会发生这种情况?如果您需要更多信息,请告诉我。

【问题讨论】:

  • 您发送的令牌是否有效(签入jwt.io)?
  • @auburg 是的

标签: asp.net-core asp.net-identity


【解决方案1】:

我认为这是使用你的中间件的问题:

        app.UseRouting();

        app.UseAuthorization();

        app.UseAuthentication();

可以通过以下方式尝试:


        app.UseAuthentication();
        app.UseRouting();

        app.UseAuthorization();

首先,我们使用验证用户 - 中间件读取令牌并将身份注入 http 上下文

【讨论】:

  • 谢谢,这就是问题所在。
  • 很高兴,我可以帮忙:)
猜你喜欢
  • 2019-09-09
  • 2017-08-18
  • 2019-06-23
  • 2017-07-27
  • 2019-10-20
  • 2016-01-17
  • 2020-08-23
  • 1970-01-01
  • 2018-03-07
相关资源
最近更新 更多