.NetCore JwtBearerAuthentication不拒绝过期的令牌

时间:2017-05-30 01:12:06

标签: c# asp.net-core jwt asp.net-core-identity

我正在生成JWT以与我的WebApi项目一起使用。我将令牌设置为在一分钟内到期,以便我可以测试它是否在到期日期之后提交时拒绝令牌。

CreateToken控制器

public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
{
    var user = await _unitOfWork.UserManager.FindByNameAsync(model.UserName);

    if (user == null) return BadRequest();
    if (Hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) !=
        PasswordVerificationResult.Success) return BadRequest();

    var userClaims = await UserManager.GetClaimsAsync(user);

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), 
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email)
    }
    .Union(userClaims);

    var cert = new Certificate(Configuration["Tokens:Certificate"]);
    var token = new JwtSecurityToken(
        issuer: Configuration["Tokens:Issuer"],
        audience: Configuration["Tokens:Audience"],
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(1),
        signingCredentials: cert.Signature
    );

    return Ok(new
    {
        token = new JwtSecurityTokenHandler().WriteToken(token),
        expiration = token.ValidTo
    });
}

令牌身份验证 - 启动类

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = Configuration["Tokens:Issuer"],
        ValidAudience = Configuration["Tokens:Audience"],
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new Certificate(Configuration["Tokens:Certificate"]).SecurityKey,
        ValidateLifetime = true
    },
});

虽然我设置了validateLifetime = true,但两分钟后不会拒绝tokes。它将继续接受令牌。是否存在我不知道的最短到期时间或我的设置错误?

1 个答案:

答案 0 :(得分:12)

如果有人有兴趣,我偶然发现了答案here

library(dplyr)
new <- over %>%
  bind_cols(under) %>%
  mutate(new = 0) %>%
  mutate(new = ifelse(over < 0.05, 1, new)) %>%
  mutate(new = ifelse(under < 0.05, -1, new)) %>%
  select(new) %>%
  as.matrix()

new
     new
[1,]   0
[2,]  -1
[3,]   1
[4,]  -1
[5,]  -1