簡體   English   中英

訪問令牌過期時,Web API刷新令牌不刷新

[英]Web API refresh token not refreshing when access token is expired

在我的Web API中,我正在實現基於owin承載令牌的身份驗證,在我的客戶端應用中,我想在刷新令牌過期時使用刷新令牌刷新訪問令牌,這就是為什么我將訪問令牌的到期時間設置為僅15分鍾並將刷新令牌設置為1小時。 我的原始訪問令牌過期后,即使我的刷新令牌一直有效,我也無法刷新訪問令牌,但是當訪問令牌有效時,它仍然可以正常工作。 下面是我的代碼。

public override void Create(AuthenticationTokenCreateContext context)
        {
            Guid Token = Guid.NewGuid();
            using (InfoSystemEntities dbContext = new InfoSystemEntities())
            {
                RefreshToken RToken = new RefreshToken()
                {
                    Token = Token,
                    IssueDateUtc = DateTime.UtcNow,
                    ExpiryDateUtc = DateTime.UtcNow.AddMinutes(Params.RefreshPasswordExpiryInMinutes),
                    IssuedTo = context.Ticket.Identity.GetUserId<int>()
                };

                context.Ticket.Properties.IssuedUtc = RToken.IssueDateUtc;
                context.Ticket.Properties.IssuedUtc = RToken.ExpiryDateUtc;

                RToken.ProtectedTicket = context.SerializeTicket();
                dbContext.RefreshTokens.Add(RToken);

                if (dbContext.SaveChanges() > 0)
                {
                    context.SetToken(Token.ToString());
                    //context.SetToken(context.SerializeTicket());
                }
            }
        }

        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            using (InfoSystemEntities dbContext = new InfoSystemEntities())
            {
                Guid Token = Guid.Parse(context.Token);
                RefreshToken RToken = dbContext.RefreshTokens.Where(T => T.Token == Token).FirstOrDefault();

                if (RToken != null)
                {
                    if (RToken.ExpiryDateUtc > DateTime.UtcNow)
                    {
                        context.DeserializeTicket(RToken.ProtectedTicket);
                    }
                    else
                    {
                        context.Response.Write("refresh_token not found or expired");
                    }

                    //dbContext.RefreshTokens.Attach(RToken);
                    //dbContext.RefreshTokens.Remove(RToken);
                    //dbContext.SaveChanges();
                }
                else
                {
                    context.Response.Write("refresh_token not found or expired");
                }
            }
        }

public class OAuthProvider : OAuthAuthorizationServerProvider
    {
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //MyUserManager CustomUserManager = HttpContext.Current.GetOwinContext().GetUserManager<MyUserManager>();
            MyUserManager CustomUserManager = new MyUserManager();

            var user = await CustomUserManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                context.Rejected();
                return;
            }

            if (!user.IsActive)
            {
                context.SetError("invalid_grant", "The user account is disabled");
                context.Rejected();
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("FullName", user.FirstName + " " + user.LastName));
            // Optional : You can add a role based claim by uncommenting the line below.
            identity.AddClaim(new Claim("Role", user.Role));
            identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));

            var props = new AuthenticationProperties(new Dictionary<string, string> { { "firstname", user.FirstName }, { "lastname", user.LastName }, { "email", user.UserName }, { "role", user.Role }, { "refresh_token_expires_in", (Params.RefreshPasswordExpiryInMinutes * 60).ToString() } });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }


        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (context.ClientId == null)
                context.Validated();

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

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

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

        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            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);
        }
    }

在context.Ticket.Properties.IssuedUtc = RToken.ExpiryDateUtc中檢查您的代碼; 應該是ExpiresUtc而不是IssuedUtc

暫無
暫無

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

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