public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();

            // copy all properties and set the desired lifetime of refresh token
            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
            };

            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            _refreshTokens.TryAdd(guid, refreshTokenTicket);

            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
Example #2
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            Guid guid = Guid.NewGuid();

            // maybe only create a handle the first time, then re-use for same client
            // copy properties and set the desired lifetime of refresh token
            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddDays(30)
            };
            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            //_refreshTokens.TryAdd(guid, context.Ticket);
            _refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);

            context.SetToken(guid.ToString());
        }
        /// <summary>
        /// Name: CreateAsync
        /// Description: Method to create async context
        /// </summary>
        /// <param name="context">Context</param>
        /// <returns>Task</returns>
        #pragma warning disable 1998
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            // Define Id of refresh token
            var guid = Guid.NewGuid();
            // Serialize token
            string strRefreshToken = context.SerializeTicket();

            // Save token tracking
            this.ITokenTrackingMgr.Save(new TokenTracking()
            {
                TokenTrackingId = guid,
                Token           = strRefreshToken,
                RequestedDate   = DateTime.Now.ToUniversalTime(),
                UserId          = Guid.Parse(context.Ticket.Identity.Claims.ElementAt(0).Value)
            });
            // Set id to token
            context.SetToken(guid.ToString());
        }
Example #4
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

            //  var clientid = Convert.ToString(ConfigurationManager.AppSettings["ClientId"].ToString());
            string deviceId = Convert.ToString(HttpContext.Current.Request.Form["DeviceId"]);

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

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


            //  var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");
            var refreshTokenLifeTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshTokenExpireTime"].ToString());

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

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

            token.ProtectedTicket = context.SerializeTicket();
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddYears(60);
            token.ProtectedTicketLT = context.SerializeTicket();

            var result = await _authRepository.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }
Example #5
0
        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");

            var dependencyScope = new AutofacWebApiDependencyScope(context.OwinContext.GetAutofacLifetimeScope());
            var authRepository  = dependencyScope.GetService(typeof(IAuthRepository)) as IAuthRepository;

            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();

            try
            {
                var result = await authRepository.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
            catch (Exception ex)
            {
                var message = ex.Message;
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            try
            {
                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         = Hasher.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);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid    = context.Ticket.Properties.Dictionary["as:client_id"];
            var userid      = context.Ticket.Properties.Dictionary["userid"];
            var securityKey = context.Ticket.Properties.Dictionary["securityKey"];

            if (string.IsNullOrEmpty(clientid) || string.IsNullOrEmpty(securityKey))
            {
                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))
                //};
                var token = new LoginCacheModel()
                {
                    userid      = userid,
                    userName    = context.Ticket.Identity.Name,
                    securityKey = securityKey,
                };
                //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);
                }
            }
        }
Example #8
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();

            /* copy claims from previous token */

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30)
            };
            var refreshTokenTicket = await Task.Run(() => new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties));

            _refreshTokens.TryAdd(guid, refreshTokenTicket);

            // consider storing only the hash of the handle

            context.SetToken(guid);
        }
Example #9
0
        public void Create(AuthenticationTokenCreateContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];

            RefreshToken dticket;
            var          dlist = _refreshTokens.Where(x => x.Value.ticket.Identity.Name == context.Ticket.Identity.Name).Select(x => x.Key).ToList();

            foreach (var item in dlist)
            {
                _refreshTokens.TryRemove(item, out dticket);
            }

            if (originalClient != null)
            {
                var guid = ShortGuid.NewGuid();
                _refreshTokens.TryAdd(guid, new RefreshToken(context.Ticket));
                context.SetToken(guid);
            }
        }
Example #10
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
                                                           //ExpiresUtc = DateTime.UtcNow.AddMonths(3)
            };

            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            // maybe only create a handle the first time, then re-use
            _refreshTokens.TryAdd(guid, refreshTokenTicket);

            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
Example #11
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString("N");

            // maybe only create a handle the first time, then re-use for same client
            // copy properties and set the desired lifetime of refresh token
            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddYears(1)
            };
            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            //_refreshTokens.TryAdd(guid, context.Ticket);
            _refreshTokens.TryAdd(guid, refreshTokenTicket);

            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
        public override void Create(AuthenticationTokenCreateContext context)
        {
            //Get the claim which holds creation date
            var identity     = (ClaimsPrincipal)Thread.CurrentPrincipal;
            var creationDate = Convert.ToDateTime(identity.Claims.Where(c => c.Type == "creationDate").Single().Value);
            //Create a variable holding current time minus 30 seconds(This is how long time you can create new refresh tokens by providing your original refresh token)
            DateTime now = DateTime.UtcNow.AddSeconds(-30);


            //If the time has passed more than 30 seconds from the time you got your original access and refresh token by providing credentials
            //you may not create and return new refresh tokens(Obviously the 30  seconds could be changed to something less or more aswell)
            if (now < creationDate)
            {
                // Expiration time in seconds
                int expire = 2 * 60;
                context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
                context.SetToken(context.SerializeTicket());
            }
        }
        // ********************************************************************************
        /// <summary>
        /// create refresh token helper
        /// </summary>
        /// <param name="context"></param>
        // ********************************************************************************
        public void Create(AuthenticationTokenCreateContext context)
        {
            object inputs;

            context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

            var grantType = ((Microsoft.Owin.FormCollection)inputs)?.GetValues("grant_type");

            var grant = grantType.FirstOrDefault();

            //if (grant == null || grant.Equals("refresh_token")) return;
            if (grant == null)
            {
                return;
            }
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(30);

            context.SetToken(context.SerializeTicket());
        }
        public void Create(AuthenticationTokenCreateContext context)
        {
            var audience = context.Ticket.Properties.Dictionary["audience"];

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

            // it will be set inside CustomJwtFromat accordingly to is's expiration configuration
            var expire = context.Request.Headers["expire"];

            context.Ticket.Properties.ExpiresUtc = expire != null
                ? (DateTimeOffset?)DateTimeOffset.UtcNow.AddSeconds(Convert.ToDouble(expire))
                : null;
            var token = context.SerializeTicket();

            context.SetToken(token);
        }
        private async Task CreateAccessTokenSync(AuthenticationTokenCreateContext context)
        {
            var ticket = context.Ticket;
            var token  = ProtectedData(context);

            if (!ticket.Identity.Identifier().HasValue)
            {
                return;
            }



            await _tokenRepository.SaveAsync(token,
                                             ticket.Properties.ExpiresUtc?.UtcDateTime
                                             , ticket.Properties.IssuedUtc?.UtcDateTime
                                             , ticket.Identity.Identifier().Value);

            context.SetToken(token);
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            //Get the client ID from the Ticket properties
            var clientid = context.Ticket.Properties.Dictionary["client_id"];

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

            //Generating a Uniqure Refresh Token ID
            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                // Getting the Refesh Token Life Time From the Owin Context
                var refreshTokenLifeTime = context.OwinContext.Get <string>("ta:clientRefreshTokenLifeTime");

                //Creating the Refresh Token object
                var token = new RefreshToken()
                {
                    //storing the RefreshTokenId in hash format
                    ID          = Helper.GetHash(refreshTokenId),
                    ClientID    = clientid,
                    UserName    = context.Ticket.Identity.Name,
                    IssuedTime  = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };

                //Setting the Issued and Expired time of the Refresh Token
                context.Ticket.Properties.IssuedUtc  = token.IssuedTime;
                context.Ticket.Properties.ExpiresUtc = token.ExpiredTime;

                token.ProtectedTicket = context.SerializeTicket();

                var result = await _repo.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
        /// <summary>
        /// Creates a new refresh token.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>A promise.</returns>
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            RemoveExpiredTokens();

            Guid refreshToken = Guid.NewGuid();

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(5)
            };

            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
            // consider storing only the hash of the handle
            RefreshTokens.TryAdd(refreshToken, refreshTokenTicket);
            context.SetToken(refreshToken.ToString("N"));
        }
Example #18
0
        public override void Create(AuthenticationTokenCreateContext context)
        {
            // make a random value
            var bytes = new byte[256 / 8];

            _rng.GetBytes(bytes);
            var nonce = TextEncodings.Base64Url.Encode(bytes);

            // add it as an extra property
            context.Ticket.Properties.Dictionary["nonce"] = nonce;
            lock (_sync)
            {
                // and make this server remember it was produced
                _outstanding[nonce] = context.Ticket.Properties.ExpiresUtc;
            }

            // the access code is the serialized ticket with the nonce buried in it
            context.SetToken(context.SerializeTicket());
        }
Example #19
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["clientid"];

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

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



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



            //Set the desired lifetime of refresh token
            context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            //Protected Ticket column contains signed string which contains a serialized representation for the ticket for specific user
            //In other words it contains all the claims and ticket properties for this user.
            //The Owin middle-ware will use this string to build the new access token auto-magically
            token.ProtectedTicket = context.SerializeTicket();

            var result = _hPayDomain.AddRefreshToken(token);

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

            return;
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["userName"];

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

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

            using (AuthRepository _repo = new AuthRepository())
            {
                if (context.Ticket.Properties.ExpiresUtc != null)
                {
                    if (context.Ticket.Properties.IssuedUtc != null)
                    {
                        var refreshTokenLifeTime = context.Ticket.Properties.ExpiresUtc.Value.Subtract(context.Ticket.Properties.IssuedUtc.Value);

                        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.TotalMinutes))
                        };

                        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 CreateAsync(AuthenticationTokenCreateContext context)
        {
            using (var requestScope = _ioc.BeginLifetimeScope("AutofacWebRequest"))
            {
                var tokenService = requestScope.Resolve(typeof(IRefreshTokenService)) as IRefreshTokenService;
                var clientId     = context.Ticket.Properties.Dictionary["client_id"];

                if (string.IsNullOrEmpty(clientId))
                {
                    await Task.CompletedTask;
                }

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

                var refreshTokenLifeTimeInDays = Convert.ToInt16(ConfigurationManager.AppSettings["RefreshTokenLifeTimeInDays"]);
                var token = new RefreshTokenDTO
                {
                    Id             = CryptoHelper.GetHash(refreshTokenId),
                    Subject        = context.Ticket.Identity.GetUserId(),
                    IssuedUtc      = DateTime.UtcNow,
                    ExpiresUtc     = DateTime.UtcNow.AddDays(refreshTokenLifeTimeInDays),
                    OrganizationId = context.Ticket.Identity.GetOrganizationId()
                };

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

                token.ProtectedTicket = context.SerializeTicket();
                var userOrg = new UserAndOrganizationDTO
                {
                    OrganizationId = context.Ticket.Identity.GetOrganizationId(),
                    UserId         = context.Ticket.Identity.GetUserId()
                };

                tokenService?.RemoveTokenBySubject(userOrg);
                tokenService?.AddNewToken(token);

                context.SetToken(refreshTokenId);
            }

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

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

            //TODO: I removed hashed tokens to reduce database size

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

            var service = WebApiTokenEN.GetService("");


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

            WebApiToken token = WebApiTokenEN.GetEntityObjectT();

            token.WebApiTokenID   = Guid.NewGuid();
            token.WebApiClientID  = WebApiClientEN.GetService().GetByClientCode(clientid).WebApiClientID;
            token.UserID          = Convert.ToInt64(context.Ticket.Identity.Name);
            token.IssuedUtc       = DateTime.UtcNow;
            token.ExpiresUtc      = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime));
            token.ProtectedTicket = context.SerializeTicket();

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

            service.AddToken(token);

            context.SetToken(token.WebApiTokenID.ToString("n"));
            //}
            //catch (Exception ex)
            //{
            //    var result = UIUtils.GetExceptionActionResult(ex);
            //    context.Response.
            //}
        }
Example #23
0
        public void Create(AuthenticationTokenCreateContext context)
        {
            var refreshToken = Guid.NewGuid().ToString();

            RedisKeyGenerator = RedisKeyGenerator ?? ((ctx, token) => token);

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = _configuration.ExpiresUtc
            };

            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            var key = RedisKeyGenerator(context.Ticket, refreshToken);

            Store(key, refreshTokenTicket);

            context.SetToken(refreshToken);
        }
Example #24
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(40)
            };

            var refreshTokenTicket = await Task.Run(() =>
            {
                return(new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties));
            });

            _refreshTokens.TryAdd(guid, refreshTokenTicket);


            context.SetToken(guid);
        }
Example #25
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            await Task.Run(() =>
            {
                var guid = Guid.NewGuid().ToString();

                // copy all properties and set the desired lifetime of refresh token  
                var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
                {
                    IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(60)//DateTime.UtcNow.AddYears(1)  
                };
                var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

                _refreshTokens.TryAdd(guid, refreshTokenTicket);

                // consider storing only the hash of the handle  
                context.SetToken(guid);
            });
        }
Example #26
0
        public string GenerateRefreshToken(AuthenticationTicket ticket, string userName, string accessToken)
        {
            var context = new AuthenticationTokenCreateContext(_owinContext, AuthMiddleware.AuthBearerAuthenticationOptions.AccessTokenFormat, ticket);
            var token   = new RefreshTokenRecord
            {
                Token      = accessToken,
                UserName   = userName,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddDays(1)
            };

            context.Ticket.Properties.IssuedUtc  = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(1);
            var refreshToken = context.SerializeTicket();

            token.ProtectedTicket = refreshToken;
            context.SetToken(refreshToken);
            _refreshTokenService.AddRefreshToken(token);
            return(refreshToken);
        }
Example #27
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var refreshToken = Guid.NewGuid().ToString();

            StoreKeyFunc = StoreKeyFunc ?? ((ctx, token) => token);

            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = _configuration.ExpiresUtc
            };

            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            var key = StoreKeyFunc(context.Ticket, refreshToken);

            await StoreAsync(key, refreshTokenTicket);

            context.SetToken(refreshToken);
        }
Example #28
0
        public Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var applicationProvider = context.OwinContext.Get <IApplicationProvider>("IApplicationProvider");
            var application         = context.OwinContext.Get <IApplication>("oh:application");

            if (application == null)
            {
                return(Task.FromResult <object>(null));
            }
            //--------------------------------------------------------------------------------------------------------------------
            var userId       = context.Ticket.Identity.FindFirst("Id").Value;
            var refreshToken = applicationProvider.CreateToken(application, userId);

            context.Ticket.Properties.IssuedUtc  = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(application.RefreshTokenTimeout));
            context.SetToken(refreshToken);

            applicationProvider.SaveUserToken(application, userId, refreshToken);
            return(Task.FromResult <object>(null));
        }
Example #29
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary[GenericNames.AUTHENTICATION_CLIENT_ID_KEY];

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

            var refreshTokenLifeTime = context.OwinContext.Get <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME);

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

            //var refreshTokenRepository = new RefreshTokenRepository(context.OwinContext.Get<ManahostManagerDAL>());
            /*var ClientManager = ClientUserManager.Create(null, context.OwinContext.Get<ManahostManagerDAL>());*/

            IDependencyScope        Scope                  = context.OwinContext.Get <IDependencyScope>();
            ClientUserManager       ClientManager          = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            IRefreshTokenRepository refreshTokenRepository = Scope.GetService(typeof(IRefreshTokenRepository)) as IRefreshTokenRepository;

            var ServiceRepository = new ServiceRepository(context.OwinContext.Get <ManahostManagerDAL>());

            var client = await ClientManager.FindByEmailAsync(context.Ticket.Identity.Name);

            var service = ServiceRepository.GetUniq(x => x.Id == clientId);

            var token = new RefreshToken()
            {
                Id         = refreshToken,
                Client     = client,
                Service    = service,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            token.ProtectedTicket = context.SerializeTicket();
            refreshTokenRepository.Add(token);
            await refreshTokenRepository.SaveAsync();

            context.SetToken(refreshToken);
        }
Example #30
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientName = context.Ticket.Properties.Dictionary["as:client_id"];

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

            var refreshTokenId      = Guid.NewGuid().ToString("n");
            var db                  = new MainContext();
            var repo                = new RepositoryBase <ApplicationClient>(db);
            var applicationClientId = repo.GetItemByExpression(f => f.Name.Equals(clientName))?.ApplicationClientId;

            if (!applicationClientId.HasValue)
            {
                return;
            }

            var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");
            var token = new RefreshToken
            {
                RefreshTokenId      = PasswordAssertionConcern.GetHash(refreshTokenId),
                ApplicationClientId = applicationClientId.Value,
                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 refreshTokenRepo = new RepositoryRefreshToken(db);
            var result           = refreshTokenRepo.Add(token);

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