Exemple #1
0
        public IHttpActionResult GetAccessToken(RefreshTokenModel refreshTokenModel)
        {
            ApiResponse apiResponse = new ApiResponse();

            apiResponse.Message = "Your session has expired. Kindly login again.";
            try
            {
                var getHashToken           = GenerateHash.GetHash(refreshTokenModel.RefreshToken);
                var getRefreshTokenDetails = refreshTokenRepository.GetRefreshTokenDetail(getHashToken);
                if (getRefreshTokenDetails != null && getRefreshTokenDetails.ExpiresUtc > DateTime.UtcNow && !string.IsNullOrEmpty(getRefreshTokenDetails.ProtectedTicket))
                {
                    if (getRefreshTokenDetails.DeviceType == refreshTokenModel.DeviceType)
                    {
                        var currentTime = DateTime.UtcNow;
                        Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
                        var getSecurityClaims = serializer.Deserialize(System.Text.Encoding.Default.GetBytes(getRefreshTokenDetails.ProtectedTicket));

                        //Generate New Refresh Token and Access Token
                        var tokenExpiration = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTime"]);
                        var props           = new AuthenticationProperties()
                        {
                            IssuedUtc  = currentTime,
                            ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)),
                        };

                        var ticket  = new AuthenticationTicket(getSecurityClaims.Identity, props);
                        var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                            Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);
                        context.Ticket.Properties.Dictionary.Add(new KeyValuePair <string, string>("device_id", getRefreshTokenDetails.DeviceId));
                        var accessToken          = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                        var refreshTokenId       = Guid.NewGuid().ToString("n");
                        var refreshTokenLifeTime = Convert.ToDouble(ConfigurationManager.AppSettings["RefreshTokenExpireTime"]);


                        var refreshToken = new RefreshToken()
                        {
                            RefreshTokenId = GenerateHash.GetHash(refreshTokenId),
                            DeviceId       = getRefreshTokenDetails.DeviceId,
                            DeviceType     = refreshTokenModel.DeviceType,
                            UserId         = getRefreshTokenDetails.UserId,
                            IssuedUtc      = currentTime,
                            ExpiresUtc     = currentTime.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
                        };
                        context.Ticket.Properties.IssuedUtc  = refreshToken.IssuedUtc;
                        context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
                        refreshToken.ProtectedTicket         = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));

                        //SAVE Refresh token
                        refreshTokenRepository.SaveRefreshToken(refreshToken);

                        Dictionary <string, string> tokenResponse = new Dictionary <string, string>();
                        tokenResponse.Add("access_token", accessToken);
                        tokenResponse.Add("token_type", "bearer");
                        tokenResponse.Add("expires_in", TimeSpan.FromMinutes(tokenExpiration).TotalSeconds.ToString());
                        tokenResponse.Add("issued", ticket.Properties.IssuedUtc.Value.ToString("R"));
                        tokenResponse.Add("expires", ticket.Properties.ExpiresUtc.Value.ToString("R"));
                        tokenResponse.Add("refresh_token", refreshTokenId);
                        return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, tokenResponse)));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Gone, apiResponse)));
        }