简体   繁体   English

刷新令牌在访问令牌后立即过期

[英]Refresh token expired as soon as access token

I am implementing JWT refresh token, and setting different time expire for refresh token, but it is taking expire time same as access token 我正在实现JWT刷新令牌,并为刷新令牌设置了不同的过期时间,但是它花费的访问时间与访问令牌相同

var refreshTokenId = Guid.NewGuid().ToString("n");
DateTime refreshTokenLifeTime = context.OwinContext.Get<DateTime>("as:clientRefreshTokenLifeTime");

To save in database 保存在数据库中

RefreshToken refreshToken = new RefreshToken();
refreshToken.Token = refreshTokenId;
refreshToken.PrivateKey = context.SerializeTicket();
refreshToken.ExpiryDate = refreshTokenLifeTime;

End saving Db 结束保存Db

context.Ticket.Properties.IssuedUtc = DateTime.Now;
context.Ticket.Properties.ExpiresUtc = refreshTokenLifeTime;

context.SetToken(refreshTokenId);
context.SetToken(context.SerializeTicket());

Any help what I am doing wrong? 任何帮助我做错了吗?

The refresh token does not extend the time of expiration, this is called sliding expiration and you cannot do it with access tokens. 刷新令牌不会延长过期时间,这称为滑动过期,您不能使用访问令牌来做到这一点。 I have used the refresh token to update user Roles, not the expiration time. 我已经使用了刷新令牌来更新用户角色,而不是到期时间。 Check this Link for Slidingexpiration I used the below code to refresh token and persisting it 检查此链接的滑动到期时间,我使用下面的代码刷新令牌并将其持久化

  public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{

    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

        if (string.IsNullOrEmpty(clientid))
        {
            return;
        }

        var refreshTokenId = Guid.NewGuid().ToString("n");

        using (AuthRepository _repo = new AuthRepository())
        {
            var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime"); 

            var token = new RefreshToken() 
            { 
                Id = Helper.GetHash(refreshTokenId),
                ClientId = clientid, 
                Subject = context.Ticket.Identity.Name,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) 
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            token.ProtectedTicket = context.SerializeTicket();

            var result = await _repo.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }

        }
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {

        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        string hashedTokenId = Helper.GetHash(context.Token);

        using (AuthRepository _repo = new AuthRepository())
        {
            var refreshToken = await _repo.FindRefreshToken(hashedTokenId);

            if (refreshToken != null )
            {
                //Get protectedTicket from refreshToken class
                context.DeserializeTicket(refreshToken.ProtectedTicket);
                var result = await _repo.RemoveRefreshToken(hashedTokenId);
            }
        }
    }
}

Now the request context contains all the claims stored previously for this user, and you need to add the logic which allows you to issue new claims or update the existing claims and contain them into the new access token generated before you need the add the below code in the AuthorizationServerProvider Class you have. 现在,请求上下文包含先前为此用户存储的所有声明,并且您需要添加逻辑,该逻辑允许您发出新声明或更新现有声明并将它们包含在生成的新访问令牌中,然后再添加以下代码。在AuthorizationServerProvider类中。

public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
        var currentClient = context.ClientId;

        if (originalClient != currentClient)
        {
            context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
            return Task.FromResult<object>(null);
        }

        // Change auth ticket for refresh token requests
        var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
        newIdentity.AddClaim(new Claim("newClaim", "newValue"));

        var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
        context.Validated(newTicket);

        return Task.FromResult<object>(null);
    }

This is wrong 这是错的

DateTime refreshTokenLifeTime = context.OwinContext.Get<DateTime>("as:clientRefreshTokenLifeTime");

you are reading the lifetime, not setting it to any new value. 您正在读取寿命,而不是将其设置为任何新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问令牌过期时使用刷新令牌 - Use Refresh Token When Access Token is Expired 使用JWT令牌使访问令牌过期时刷新令牌调用 - Refresh Token call when Access token expired using JWT token OWIN ASP.NET-如果访问令牌过期,则无法使用刷新令牌生成访问令牌 - OWIN ASP.NET - Cant generate Access Token using Refresh Token if Access Token is expired 访问令牌已过期,但我们无法刷新它 - The access token has expired but we can't refresh it exception 刷新过期令牌 Web API - Refresh expired token Web API 如何刷新访问令牌 - How to refresh access token 如何使用已使用V2模型保存在数据库中的令牌缓存登出到Office 365,刷新过期的访问令牌? - How to refresh the expired access token with out login to office 365 using token cache already saved in a database using V2 model? JWT 访问令牌与刷新令牌(创建) - JWT access token vs refresh token (creating) 刷新失败,并显示403禁止错误。 刷新令牌已撤消或过期 - Refresh failed with a 403 Forbidden error. The refresh token was revoked or expired 无法获取访问令牌和刷新令牌 - Unable to get Access token and Refresh token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM