【问题标题】:Asp.Net Core Identity not validating token expiry properly [duplicate]Asp.Net Core Identity 未正确验证令牌到期 [重复]
【发布时间】:2021-04-02 01:17:01
【问题描述】:

我从 .net 核心 API 发出 JWT 不记名令牌,然后由移动应用程序使用。我看到了过期时间似乎被忽略的问题 - 直到我重新启动 API。

这都是使用 Microsoft 软件包(例如,不是 IdentityServer 等第三方)

在我的 Startup.cs 我有以下配置令牌:

    services.AddAuthentication(auth =>
        {
            auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidAudience = Configuration["AuthSettings:Audience"],
                ValidIssuer = Configuration["AuthSettings:Issuer"],
                RequireExpirationTime = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthSettings:Key"])),
                ValidateIssuerSigningKey = true,
                RequireSignedTokens = true,
                ValidateLifetime = true
            };
        });

要发行令牌,我有以下代码:

public async Task<UserManagerResponse> LoginUserAsync(LoginViewModel model)
    {
        var user = await _userManager.FindByEmailAsync(model.Email);

        if (user == null)
        {
            return new UserManagerResponse
            {
                Message = "There is no user with that Email address",
                IsSuccess = false,
            };
        }

        var result = await _userManager.CheckPasswordAsync(user, model.Password);

        if (!result)
            return new UserManagerResponse
            {
                Message = "Invalid password",
                IsSuccess = false,
            };

        var claims = new[]
        {
            new Claim("Email", model.Email),
            new Claim(ClaimTypes.NameIdentifier, user.Id),
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthSettings:Key"]));

        var token = new JwtSecurityToken(
            issuer: _configuration["AuthSettings:Issuer"],
            audience: _configuration["AuthSettings:Audience"],
            claims: claims,
            expires: DateTime.Now.AddSeconds(10), //.AddMinutes(1),
            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)) ;

        string tokenAsString = new JwtSecurityTokenHandler().WriteToken(token);

        return new UserManagerResponse
        {
            Message = tokenAsString,
            IsSuccess = true,
            ExpireDate = token.ValidTo
        };
    }

例如,在 jwt.io 上解码 Token 会显示正确的到期时间(例如 10 秒或 1 分钟等)。

但是,当使用过期令牌调用 Api 时,我仍然收到 200 OK 响应,就好像令牌仍然有效一样。然后当我重新启动 Api,并使用过期的令牌调用它时,我会得到预期的 401 Unauthorized。目前通过 IIS Express 上的 Visual Studio 运行 Api。它是 .net 核心 3.1。

在这里苦苦寻找下一步该去哪里。我添加了“ValidatedLifetime = true”,它似乎没有做任何事情。

谢谢,

史蒂夫。

【问题讨论】:

  • 是的——就是这样。当我设置 ClockSkew = TimeSpan.Zero 时,它按我的预期工作

标签: asp.net asp.net-core authentication jwt bearer-token


【解决方案1】:

好的 - 看起来这是由于时钟偏差...

通过将ClockSkew = TimeSpan.Zero 添加到options.TokenValidationParameters 进行确认,然后过期令牌会导致返回未授权

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2019-11-19
    • 2020-07-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多