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

            using (AuthRepository _repo = new AuthRepository())
            {

                var token = new RefreshToken()
                {
                    Id = refreshTokenId.GetHash(),
                    Subject = context.Ticket.Identity.Name,
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(30)
                };

                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)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];
            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

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

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

            var token = new RefreshToken()
            {
                Id = HashMaker.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 authRepository.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary["client_id"];

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

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

            var token = new RefreshToken
            {
                Id = refreshTokenId,
                ClientId = clientId,
                Subject = context.Ticket.Identity.Name,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc =
                    DateTime.UtcNow.AddHours(
                        Convert.ToInt32(WebConfigurationManager.AppSettings["RefreshTokenExpiration"]))
            };

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

            token.ProtectedTicket = context.SerializeTicket();

            //TODO: store the token somewhere

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

            var clientid = context.OwinContext.Get<string>("tm:client_id");

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

            var token = new RefreshToken()
            {
                ID = HashingService.MakeHash(guid),
                client_id = clientid,
                username = context.Ticket.Identity.Name,
                issued = DateTime.UtcNow,
                expired = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

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

            token.ProtectedTicket = context.SerializeTicket();
 
            RefreshTokenService rts = new RefreshTokenService();
            var result = await rts.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(guid);
            }
        }
Example #5
0
 public override void Create(AuthenticationTokenCreateContext context)
 {
     // Expiration time in seconds
     int expire = 5 * 60;
     context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
     context.SetToken(context.SerializeTicket());
 }
        public override void Create(AuthenticationTokenCreateContext context)
        {
            if (context.Ticket.Identity.AuthenticationType == AuthenticationType.Anonymous) {
                return;
            }

            //var authTicketService = ObjectFactory.GetInstance<AuthTicketService>();
            var refreshToken = string.Empty;
            while (true) {
                refreshToken = GenerateRefreshToken();
                if (true/*!authTicketService.Exists(x => x.Id == refreshToken)*/) {
                    break;
                }
            }

            var clientId = context.Ticket.Properties.Dictionary["client_id"];
            var authTicket = new AuthTicket() {
                RefreshToken = refreshToken,
                ResourceOwner = context.Ticket.Identity.FindFirst("Email").Value,
                ClientId = context.Ticket.Properties.Dictionary["client_id"],
                AccessToken = context.SerializeTicket(),
                Issued = context.Ticket.Properties.IssuedUtc.Value.DateTime,
                Expires = context.Ticket.Properties.ExpiresUtc.Value.DateTime
            };

            //authTicketService.Create(authTicket);
            context.SetToken(authTicket.RefreshToken);
        }
 public Task CreateAsync(AuthenticationTokenCreateContext context)
 {
     return Task.Run(() =>
     {
         Create(context);
     });
 }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary["as:client_id"];
            if (string.IsNullOrWhiteSpace(clientId))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("N");
            var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifetime");
            var token = new RefreshToken
            {
                Id = AuthorizationHelpers.GetHash(refreshTokenId),
                ClientApplicationId = clientId,
                Subject = context.Ticket.Identity.Name,
                IssuedAt = DateTime.UtcNow,
                ExpiresAt = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifetime))
            };

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

            token.ProtectedTicket = context.SerializeTicket();

            if (await _userRepository.TryAddRefreshTokenAsync(token))
            {
                context.SetToken(refreshTokenId);
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Identity.Name;
            var refreshTokenId = Guid.NewGuid().ToString("n");

            var token = new RefreshToken()
            {
                Id = refreshTokenId,
                ClientId = clientid,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddSeconds(15)
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
            token.ProtectedTicket = context.SerializeTicket();

            repo.Add(refreshTokenId, token);
            await Task.Delay(1);

            context.SetToken(refreshTokenId);

            //var allowedOrigins = context.OwinContext.Get<List<string>>("as:clientAllowedOrigins");
            //context.OwinContext.Response.Headers.Add(
            //    "Access-Control-Allow-Origin",
            //    allowedOrigins.Select(x => x.ToString()).ToArray()
            //    //new[] { "*" }
            //    );

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        }
        public void Create(AuthenticationTokenCreateContext context)
        {
            var clientid = context.OwinContext.Get<string>("as:client_id");

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

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

            var appTokenService = mobSocialEngine.ActiveEngine.Resolve<IAppTokenService>();

            var tokenLifeTime = context.OwinContext.Get<string>("as:clientAccessTokenLifeTime");

            var token = new AppToken() {
                Guid = Helper.GetHash(appTokenId),
                ClientId = clientid,
                Subject = context.Ticket.Identity.Name,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(tokenLifeTime)),
                TokenType = TokenType.AccessToken
            };

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

            token.ProtectedTicket = context.SerializeTicket();

            appTokenService.Insert(token);

            context.SetToken(appTokenId);
        }
Example #11
0
    public async Task CreateAsync(AuthenticationTokenCreateContext context) {
      var clientIdValue = context.Ticket.Properties.Dictionary["as:client_id"];
      if (string.IsNullOrWhiteSpace(clientIdValue)) {
        return;
      }

      int clientId = 0;
      if (!int.TryParse(clientIdValue, out clientId)) {
        return;
      }

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

      var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");
      var issuedUtc = DateTime.UtcNow;
      var expiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime));

      context.Ticket.Properties.IssuedUtc = issuedUtc;
      context.Ticket.Properties.ExpiresUtc = expiresUtc;

      var client = new AuthenticationClient();
      var result = await client.SaveRefreshToken(new SaveRefreshTokenRequest {
        HashedToken = PasswordHelper.HashToken(token),
        ClientId = clientId,
        Username = context.Ticket.Properties.Dictionary["userName"],
        IssuedUtc = DateTime.UtcNow,
        ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
        ProtectedTicket = context.SerializeTicket()
      });

      if (result.IsSuccess) {
        context.SetToken(token);
      }
    }
 /// <summary>
 /// 创建RefreshToken,在客户端请求AccessToken的时候自动调用
 /// </summary>
 /// <param name="context"></param>
 public async override Task CreateAsync(AuthenticationTokenCreateContext context)
 {
     string clientId = context.Ticket.Properties.Dictionary["as:client_id"];
     if (string.IsNullOrEmpty(clientId))
     {
         return;
     }
     
     DateTime now = DateTime.UtcNow;
     string userName = context.Ticket.Identity.Name;
     if (clientId == userName)
     {
         return;
     }
     RefreshTokenInfo tokenInfo = new RefreshTokenInfo()
     {
         Value = Guid.NewGuid().ToString("N"),
         IssuedUtc = now,
         ExpiresUtc = now.AddDays(30),
         UserName = userName,
         ClientId = clientId
     };
     context.Ticket.Properties.IssuedUtc = tokenInfo.IssuedUtc;
     context.Ticket.Properties.ExpiresUtc = tokenInfo.ExpiresUtc;
     tokenInfo.ProtectedTicket = context.SerializeTicket();
     if (await _clientRefreshTokenStore.SaveToken(tokenInfo))
     {
         context.SetToken(tokenInfo.Value);
     }
 }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (var ctx = new ApplicationDbContext())
            {
                var token = new RefreshToken()
                {
                    Id = Helper.GetHash(refreshTokenId),
                    Subject = context.Ticket.Identity.Name,
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddDays(30)
                };

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

                token.ProtectedTicket = context.SerializeTicket();

                var result = await ctx.AddRefreshToken(token);

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

            }

        }
        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 refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");
            var token = new DataLayer.Entities.User.RefreshTokens()
            {
                refreshTokenId = SharedServices.HashingService.GetHash(refreshTokenId),
                clientId = clientId,
                subject = context.Ticket.Identity.Name,
                issuedUTC = DateTime.UtcNow,
                expiredUTC = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

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

            token.protectedTicket = context.SerializeTicket();

            var tokenObj = new BusinessLogic.Identity.RefreshTokens();
            var result = await tokenObj.Insert(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }
        public virtual 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");

            await Task.Run(() => {

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

                var token = new OAuthRefreshToken()
                {
                    Key = refreshTokenId.GenerateHash(),
                    ClientId = clientId,
                    Subject = context.Ticket.Identity.Name,
                    UserType = UserType.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();

                this._oauthStore.AddRefreshToken(token);

            });

            context.SetToken(refreshTokenId);
        }
 public async Task CreateAsync(AuthenticationTokenCreateContext context)
 {
     string clientid = context.Ticket.Properties.Dictionary["as:client_id"];
     if (!string.IsNullOrEmpty(clientid))
     {
         string refreshTokenId = Guid.NewGuid().ToString("n");
         UnityContainer unityContainer = UnityConfig.GetConfiguredContainer() as UnityContainer;
         IRefreshTokenBll refreshTokenBll = UnityContainerExtensions.Resolve<IRefreshTokenBll>((IUnityContainer)unityContainer);
         string refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");
         RefreshToken token = new RefreshToken()
         {
             Id = ApplicationOAuthProvider.GetSecretHash(refreshTokenId),
             ClientId = clientid,
             Subject = context.Ticket.Identity.Name,
             IssuedUtc = DateTime.UtcNow,
             ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
         };
         context.Ticket.Properties.IssuedUtc = new DateTimeOffset?((DateTimeOffset)token.IssuedUtc);
         context.Ticket.Properties.ExpiresUtc = new DateTimeOffset?((DateTimeOffset)token.ExpiresUtc);
         token.ProtectedTicket = context.SerializeTicket();
         int result = await refreshTokenBll.InsertRefreshToken(token);
         if (result > 0)
         {
             context.SetToken(refreshTokenId);
             if (!string.IsNullOrEmpty(this.CurrentToken))
                 await this.LogHistory(LoginType.RefreshToken, LoginStatus.Success, clientid, token.Subject, this.CurrentToken, (string)null, (string)null);
         }
         else if (!string.IsNullOrEmpty(this.CurrentToken))
             await this.LogHistory(LoginType.RefreshToken, LoginStatus.ErrorAddRefreshToken, clientid, token.Subject, this.CurrentToken, (string)null, (string)null);
     }
 }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];
            var refreshTokenLifetime = context.OwinContext.Get<string>("as:RefreshTokenLifetime");

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

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

            context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifetime));
            var token = context.SerializeTicket();

            var refreshDto = new RefreshTokenDto()
            {
                Id = refreshTokenId,
                ClientId = clientid,
                Subject = context.Ticket.Identity.Name,
                Token = token
            };

            await _redisRepo.InsertRefreshTokenAsync(refreshDto);

            context.SetToken(refreshTokenId);
        }
        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");

            //TODO: support multiple clients
            //
            //http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/
            //https://github.com/thinktecture/Thinktecture.IdentityServer.v3/blob/1b33386e6ba29242293e20d806c2ad15a5bcf8ec/source/Core/Services/Default/DefaultRefreshTokenService.cs


            // 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.Now.AddMinutes(1)
            //};

            //var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
            //_refreshTokens.TryAdd(guid, context.Ticket);
            //_refreshTokens.TryAdd(guid, refreshTokenTicket);
            context.Ticket.Properties.IssuedUtc = DateTime.Now;
            context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddDays(1));

            context.SetToken(context.SerializeTicket());
            //context.SetToken(refreshTokenTicket.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void Create(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

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

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

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

            var token = new AuthenticationRefreshToken
            {
                Id = HelperMethods.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();

            AuthenticationRefreshTokenService.Save(token);

            context.SetToken(refreshTokenId);
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            if (!context.OwinContext.Environment.ContainsKey(IS_REFREHTOKEN_EXPIRED_NAME) || (bool)context.OwinContext.Environment[IS_REFREHTOKEN_EXPIRED_NAME])
            {
                bool result = false;
                var refreshTokenId = Guid.NewGuid().ToString("n");
                var clientId = context.Ticket.Properties.Dictionary["audience"];

                var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime") ?? "30";
                var token = new RefreshToken()
                {
                    Id = Utilities.GetHash(refreshTokenId),
                    ClientId = clientId,
                    Subject = context.Ticket.Identity.Name,
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddDays(Double.Parse(refreshTokenLifetime))
                };
                context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

                token.ProtectedTicket = context.SerializeTicket();

                using (IApplicationRepository rep = new ApplicationRepository())
                {
                    result = await rep.RefreshTokens.AddAsync(token);
                }
                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
        /// <summary>
        /// 生成 refresh_token
        /// </summary>
        public override void Create(AuthenticationTokenCreateContext context)
        {
            context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);

            context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
            RefreshTokens[context.Token] = context.SerializeTicket();
        }
 /// <summary>
 /// 创建RefreshToken
 /// </summary>
 /// <param name="context"></param>
 public override void Create(AuthenticationTokenCreateContext context)
 {
     string token = Guid.NewGuid().ToString("N");
     DateTime now = DateTime.UtcNow;
     context.Ticket.Properties.IssuedUtc = now;
     context.Ticket.Properties.ExpiresUtc = now.AddDays(60);
     _refreshTokens[token] = context.SerializeTicket();
     context.SetToken(token);
 }
        private void CreateRefreshToken(AuthenticationTokenCreateContext context)
        {
            var isTrusted = bool.Parse(context.Ticket.Identity.Claims.FirstOrDefault(c => c.Type == "sidekick.client.istrusted").Value);

            if (isTrusted)
            {
                context.SetToken(context.SerializeTicket());
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            try
            {
                var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

                if (string.IsNullOrEmpty(clientid))
                    return;

                // Gera um ID unico para o RefreshToken
                var refreshTokenId = Guid.NewGuid().ToString("n");

                // Pega o tempo de expiração (em minuto) do token do contexto do Owin
                var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");

                // Identifica o Browser
                var userAgent = HttpContext.Current.Request.UserAgent;
                var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
                var factory = new BrowserCapabilitiesFactory();
                factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
                var browser = userBrowser.Browser;

                var issuedUtc = DateTime.UtcNow;
                var expiresUtc = issuedUtc.AddMinutes(3); //issuedUtc.AddMonths(Convert.ToInt32(refreshTokenLifeTime));

                // Define os dados do RefreshToken
                var token = new RefreshToken
                {
                    Id = HashHelper.GetHash(refreshTokenId),
                    ClientId = clientid,
                    Browser = browser,
                    Subject = context.Ticket.Identity.Name,
                    IssuedUtc = issuedUtc,
                    ExpiresUtc = expiresUtc
                };

                // Define o IssuedUtc e o ExpiresUtc do ticket para determinar o quanto tempo o token vai ser válido
                context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

                // Serializa o ticket para ser gravado na base de dados
                var ticketSerializer = new TicketSerializer();
                token.ProtectedTicket = ticketSerializer.Serialize(context.Ticket);

                // Grava o ticket na base de dados
                var refreshTokenDomain = DependecyConfig.Container.GetInstance<IRefreshTokenDomain>();
                var result = await refreshTokenDomain.CreateAsync(token);

                if (result)
                    context.SetToken(refreshTokenId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public async Task CreateAsync(AuthenticationTokenCreateContext context)
 {
     await Task.Run(() =>
     {
         int expire = 1 * 60;
         context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
         context.SetToken(context.SerializeTicket());
     });
    
 }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

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

            _refreshTokens.TryAdd(guid, context.Ticket);

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

            // maybe only create a handle the first time, then re-use for same client
            RefreshTokens.TryAdd(guid, context.Ticket);

            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            // Generate token
            var token = Encryption.GenerateRandomString(32);
            // Get the client id
            var clientId = context.Ticket.Properties.Dictionary["as:client_id"];
            // No client id? No token.
            if (string.IsNullOrWhiteSpace(clientId))
            {
                return;
            }

            // Store the refresh token in the database
            using (var ctx = new ApplicationDbContext())
            {
                // Get the username
                var username = context.Ticket.Identity.Name;

                // Find any existing refresh tokens for the user/client and remove them
                var existingTokens = ctx.RefreshTokens.Where((x) => x.ClientId == clientId && x.Username == username);

                // Delete the existing tokens
                ctx.RefreshTokens.RemoveRange(existingTokens);

                // Get the access token time to live (ttl)
                var refreshTokenTTL = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshTokenTTL"]);

                // Create refresh token
                var rt = new RefreshToken()
                {
                    Id = Encryption.Hash(token),
                    Username = username,
                    ClientId = clientId,
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddSeconds(refreshTokenTTL)
                };

                // Set token
                context.Ticket.Properties.IssuedUtc = rt.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = rt.ExpiresUtc;

                // Serialize the ticket
                rt.Ticket = context.SerializeTicket();

                // Add to refresh tokens table
                ctx.RefreshTokens.Add(rt);

                // Save
                await ctx.SaveChangesAsync();
            }

            // Add original token to ticket
            context.SetToken(token);

        }
 public virtual void Create(AuthenticationTokenCreateContext context)
 {
     if (OnCreateAsync != null && OnCreate == null)
     {
         throw new InvalidOperationException(Resources.Exception_AuthenticationTokenDoesNotProvideSyncMethods);
     }
     if (OnCreate != null)
     {
         OnCreate.Invoke(context);
     }
 }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            if (context.Ticket.Properties.Dictionary["as:type"] != "admin")
            {
                var refreshToken = CreateRefreshTokenEntity(context);
                var command = CreateCommand(refreshToken);

                context.SetToken(refreshToken.RefreshTokenValue.ToString());
                //TODO Do we need persist before Send CreateRefreshToken, CreateUserDevice then delete?
                this.commandBus.Send(command);
            }
        }
Example #31
0
 private void CreateAuthenticationCode(Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context) {
     context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
     _authenticationCodes[context.Token] = context.SerializeTicket();
 }