public void Create(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["client_id"];

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

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

            var refreshTokenLifeTime = context.OwinContext.Get <string>("clientRefreshTokenLifeTime");

            var token = new RefreshToken()
            {
                RefreshTokenId = 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();
            Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer
                = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();

            token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));

            context.SetToken(refreshTokenId);
        }
Пример #2
0
        private Dictionary <string, string> GenerateTokenResponse(AppUser appUser, List <UserRoles> userRoles, string deviceId, DeviceType deviceType)
        {
            var            tokenExpiration = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTime"]);
            ClaimsIdentity identity        = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, appUser.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, appUser.Id.ToString()));
            identity.AddClaim(new Claim("displayName", appUser.Name));


            foreach (var userrole in userRoles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, userrole.RoleName));
            }
            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)),
            };
            var ticket  = new AuthenticationTicket(identity, props);
            var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);

            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),
                UserId         = appUser.Id,
                IssuedUtc      = DateTime.UtcNow,
                ExpiresUtc     = DateTime.UtcNow.AddMinutes(refreshTokenLifeTime),
                DeviceId       = deviceId,
                DeviceType     = deviceType
            };

            context.Ticket.Properties.IssuedUtc  = refreshToken.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
            Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
            refreshToken.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));

            //Save new 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);
            tokenResponse.Add("user_name", appUser.UserName);
            tokenResponse.Add("display_name", appUser.Name);
            return(tokenResponse);
        }
Пример #3
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)));
        }