JWT令牌未过期

时间:2019-06-04 05:15:11

标签: jwt asp.net-core-webapi asp.net-core-2.1 jwt-auth

我正在使用.net核心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;
});

登录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;

验证过滤器以验证令牌:

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
    };
}

可能是什么问题?

0 个答案:

没有答案