我正在使用JWT承载认证中间件和ASP.NET核心标识开发ASP.NET Core WebAPI .

Startup.cs :

app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = new TokenValidationParameters()
            {
               ...
            }
        });

AuthController.cs

[ValidateModel]
    [HttpPost("api/auth/token")]
    public async Task<IActionResult> Token([FromBody] Credential model)
    {
        try
        {
            var applicationUser = await _userManager.FindByEmailAsync(model.Email);
            if (applicationUser != null)
            {
                if (_hasher.VerifyHashedPassword(applicationUser, applicationUser.PasswordHash, model.Password) == PasswordVerificationResult.Success)
                {
                    var token = await CreateTokenAsync(applicationUser);

                    return Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"Exception thrown while creating JWT: {ex}");
        }

        return BadRequest("Failed to generate token");
    }

一切正常 . 当我尝试访问顶部有[Authorize]属性的控制器时,如果丢失了承载头,则获得401,否则为200 .

我想进一步确保用户只能检索自己的数据 .

生成的令牌有效负载包含以下信息:

{
  "sub": "mail@test.com",
  "jti": "user Guid in database",
  "exp": someexpirationdate,
  "iss": "http://someurl",
  "aud": "http://someurl"
}

如何在控制器的方法中访问jti值以确保用户实际上要求属于它们的资源?

EDIT

这看起来好吗?

var test = User.FindFirst(ClaimTypes.NameIdentifier).Value;

if(test != id.ToString())
{
    return BadRequest("Failed to get user");
}

其中“id”是我的行动的Guid参数

谢谢