Example #1
0
        /// <summary>
        /// Renew an access token by exchanging it with the given refresh token
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public AuthInfo RenewAccessToken(AuthInfo request)
        {
            var tokenRecord = tokenRepository.GetByRefreshToken(request.RefreshToken);

            if (tokenRecord == null)
            {
                throw new InvalidTokenException("Invalid refresh token.");
            }

            //Access token should be verified.
            //because on the token storage it's been save as a paired token (access and refresh token are saved together)
            if (tokenRecord.AccessToken != request.AccessToken)
            {
                throw new InvalidTokenException("Invalid access token.");
            }

            if (tokenRecord.BlackListed)
            {
                throw new InvalidTokenException("Token is blacklisted.");
            }

            if (tokenRecord.ExpiredAt.Subtract(DateTime.Now).TotalSeconds <= 0)
            {
                throw new InvalidTokenException("Refresh token is expired.");
            }

            var memberID = tokenHandler.GetSubValue(tokenRecord.AccessToken);
            var member   = memberRepository.GetById(memberID);

            if (member == null)
            {
                throw new UserNotFoundException();
            }

            var newAccessToken  = tokenHandler.GenerateAccessToken(member);
            var newRefreshToken = tokenHandler.GenerateRefreshToken();

            var now = DateTime.Now;

            tokenRepository.BlackList(tokenRecord.ID);

            tokenRepository.Add(new Token()
            {
                AccessToken  = newAccessToken,
                RefreshToken = newRefreshToken,
                BlackListed  = false,
                ExpiredAt    = now.AddDays(5),
                CreatedAt    = now,
            });

            return(new AuthInfo
            {
                AccessToken = newAccessToken,
                RefreshToken = newRefreshToken
            });
        }
Example #2
0
 /// <summary>
 /// Get member id from access token
 /// </summary>
 /// <returns></returns>
 protected int GetMemberIDFromToken()
 {
     return(tokenHandler.GetSubValue(GetAuthorizationHeaderValue()));
 }