0

我正在开发.net core api 2.1,我已经实现了 JWT 令牌身份验证,我希望 jwt 令牌在给定时间后过期,但它不会过期。即使在到期时间之后,令牌仍然有效。

Startup.cs 代码:

// configure jwt authentication
var jwtSettings = jwtSettingsSection.Get<JWTSettings>();
var key = Encoding.ASCII.GetBytes(jwtSettings.SECRET);
services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ClockSkew = TimeSpan.Zero
    };
});

services.Configure<IISOptions>(options =>
{
    options.AutomaticAuthentication = true;
    //options.ForwardClientCertificate = true;
});

用于在登录时创建令牌的 SignIn api 代码:

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.SECRET);
var currentTime = DateTime.Now;

var tokenDescriptor = new SecurityTokenDescriptor
{
     Expires = DateTime.Now.AddMinutes(2),
     SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
rs.Token = tokenString;

Auth 过滤器以验证令牌:

public void OnAuthorization(AuthorizationFilterContext filterContext)
{
    if (!ValidateToken(filterContext.HttpContext.Request.Headers["TOKEN"]))
    {
    filterContext.Result = new UnauthorizedResult();
    }
}

private bool ValidateToken(string authToken)
{
    try
    {
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = GetValidationParameters();

    SecurityToken validatedToken;
    IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
    return true;
    }
    catch(Exception ex)
    {
    return false;
    }
}

private TokenValidationParameters GetValidationParameters()
{
    return new TokenValidationParameters()
    {
    ValidateLifetime = false, // Because there is expiration in the generated token
    ValidateAudience = false, // Because there is no audiance in the generated token
    ValidateIssuer = false,   // Because there is no issuer in the generated token
    //ValidIssuer = _appSettings.ValidIssuer,
    //ValidAudience = _appSettings.ValidAudience,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretkey)) // The same key as the one that generate the token
    };
}

可能是什么问题?

4

0 回答 0