簡體   English   中英

ASP.NET Core MVC JWT過期時間過早

[英]ASP.NET Core MVC JWT expires too early

我正在開發mob應用程序后端,並且正在使用JWT。 我的問題是它會提前過期,我想我將它設置了365天。 我在VS2015中使用asp.net核心mvc v1。

這是我對JWT的Auth配置。 從Startup類調用此方法。

private void ConfigureAuth(IApplicationBuilder app)
    {
        secretKey = Guid.NewGuid().ToString();

        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

    app.UseSimpleTokenProvider(new TokenProviderOptions
    {
        Path = "/api/token",
        Audience = Audience,
        Issuer = Issuer,
        SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
        IdentityResolver = GetIdentity,
    });

    var tokenValidationParameters = new TokenValidationParameters
    {
        // The signing key must match!
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,

        // Validate the JWT Issuer (iss) claim
        ValidateIssuer = true,
        ValidIssuer = Issuer,

        // Validate the JWT Audience (aud) claim
        ValidateAudience = true,
        ValidAudience = Audience,

        // Validate the token expiry
        ValidateLifetime = true,

        // If you want to allow a certain amount of clock drift, set that here:
        ClockSkew = TimeSpan.Zero
    };

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        AuthenticationScheme = "Cookie",
        CookieName = "access_token",
        TicketDataFormat = new CustomJwtDataFormat(SecurityAlgorithms.HmacSha256, tokenValidationParameters),
        Events = new CustomCookieAuthenticationEvents()
    });
}

private Task<ClaimsIdentity> GetIdentity(string email)
{
    ServiceMessage<UserEntity> request = _userService.FindByEmailAsync(email).Result;

    if (request != null && request.Success && request.ResultObject != null)
    {
        return Task.FromResult(CreateClaimsIdentity(request.ResultObject, "Token"));
    }

    // Credentials are invalid, or account doesn't exist
    return Task.FromResult<ClaimsIdentity>(null);
}

private ClaimsIdentity CreateClaimsIdentity(UserEntity user, string authenticationType)
{
    List<Claim> claimCollection = new List<Claim>
    {
        new Claim(ClaimTypes.NameIdentifier, user.Email, ClaimValueTypes.String),
        new Claim(ClaimTypes.Role, user.Role, ClaimValueTypes.String),
        new Claim(ClaimTypes.Name, user.Email.Split('@')[0], ClaimValueTypes.String),
        new Claim(ClaimTypes.Expiration, TimeSpan.FromDays(365).ToString(), ClaimValueTypes.DaytimeDuration)
    };

    ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, authenticationType);

    return claimsIdentity;
}

在我的令牌提供者中間件中,我生成的JWT是這樣的:

DateTime now = DateTime.Now;

            // Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims.
            // You can add other claims here, if you want:
            Claim[] claims = new Claim[]
            {
                new Claim(ClaimTypes.Name,validation.ResultObject.Email,ClaimValueTypes.String),
                new Claim(JwtRegisteredClaimNames.Email, validation.ResultObject.Email),
                new Claim(JwtRegisteredClaimNames.Aud, Audience),
                new Claim(JwtRegisteredClaimNames.Iss, issuer),
                new Claim(JwtRegisteredClaimNames.Typ, validation.ResultObject.Role),
                new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimTypes.Role, "user")
            };

            // Create the JWT and write it to a string
            JwtSecurityToken jwt = new JwtSecurityToken
            (
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials
            );
            string encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in = (int)_options.Expiration.TotalSeconds
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));

_options是下一個類:

public class TokenProviderOptions
    {
        /// <summary>
        /// The relative request path to listen on.
        /// </summary>
        /// <remarks>The default path is <c>/token</c>.</remarks>
        public string Path { get; set; } = "api/token";

        /// <summary>
        ///  The Issuer (iss) claim for generated tokens.
        /// </summary>
        public string Issuer { get; set; }

        /// <summary>
        /// The Audience (aud) claim for the generated tokens.
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// The expiration time for the generated tokens.
        /// </summary>
        /// <remarks>The default is five minutes (300 seconds).</remarks>
        public TimeSpan Expiration { get; set; } = TimeSpan.FromDays(360);

        /// <summary>
        /// The signing key to use when generating tokens.
        /// </summary>
        public SigningCredentials SigningCredentials { get; set; }

        /// <summary>
        /// Resolves a user identity given a username and password.
        /// </summary>
        public Func<string, Task<ClaimsIdentity>> IdentityResolver { get; set; }

        /// <summary>
        /// Generates a random value (nonce) for each generated token.
        /// </summary>
        /// <remarks>The default nonce is a random GUID.</remarks>
        public Func<Task<string>> NonceGenerator { get; set; } = new Func<Task<string>>(() => Task.FromResult(Guid.NewGuid().ToString()));

一段時間后,我收到錯誤消息,但仍然不知道出了什么問題。 錯誤消息是:

WWW-Authenticate:Bearer error =“ invalid_token”,error_description =“簽名無效”

如果您需要,我可以提供更多代碼。 n

我意識到我的secretKey是由GIUD生成的,每次您關閉並重新打開移動應用程序時,都會生成新的GUID,因為舊令牌不再有效。 秘密必須是恆定的。 將其存儲在您的json配置文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM