public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var url = string.Format(_tokenValidationEndpoint, context.Token);
            
            var response = await _client.GetAsync(url);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            var jsonString = await response.Content.ReadAsStringAsync();
            var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

            var claims = new List<Claim>();

            foreach (var item in dictionary)
            {
                var values = item.Value as IEnumerable<object>;

                if (values == null)
                {
                    claims.Add(new Claim(item.Key, item.Value.ToString()));
                }
                else
                {
                    foreach (var value in values)
                    {
                        claims.Add(new Claim(item.Key, value.ToString()));
                    }
                }
            }

            context.SetTicket(new AuthenticationTicket(new ClaimsIdentity(claims, _authenticationType), new AuthenticationProperties()));
        }
 public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     return Task.Run(() =>
     {
         Receive(context);
     });
 }
    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
      try
      {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        var hashedTokenId = Helper.GetHash(context.Token);
        using (IRepository rep = new ApplicationRepository())
        {
          var refreshToken = await rep.RefreshTokens.FindAsync(hashedTokenId);

          if (refreshToken != null)
          {
            //Get protectedTicket from refreshToken class
            context.DeserializeTicket(refreshToken.ProtectedTicket);
            var result = await rep.RefreshTokens.RemoveAsync(hashedTokenId);
          }
        }

      }
      catch (Exception e)
      {
        
        throw e;
      }
    }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            try
            {

                var hashedTokenId = HashHelper.GetHash(context.Token);


                using (AuthRepository authService = new AuthRepository())
                {
                    var refreshToken = authService.FindRefreshToken(hashedTokenId);                   

                    if (refreshToken != null)
                    {
                        //Get protectedTicket from refreshToken class
                        context.DeserializeTicket(refreshToken.ProtectedTicket);
                        //remove token from db 
                        var result = authService.RemoveRefreshToken(hashedTokenId);
                    }
                }

            }
            catch (Exception ex)
            {
                Logger.Error("Error receiving token: " + ex.InnerException);
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

            if (context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Origin"))
            {
                context.OwinContext.Response.Headers["Access-Control-Allow-Origin"] = allowedOrigin;
            }
            else
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {allowedOrigin});
            }

            var hashedTokenId = TokenHelper.GetHash(context.Token);

            using (var _repo = new AuthRepository())
            {
                var refreshToken = await _repo.FindRefreshToken(hashedTokenId);

                if (refreshToken != null)
                {
                    //Get protectedTicket from refreshToken class
                    context.DeserializeTicket(refreshToken.ProtectedTicket);
                    var result = await _repo.RemoveRefreshToken(hashedTokenId);
                }
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {            
            //PIN lockout not yet implemented. Might integrated with account lockout or its own thing
            //Uncomment this to accept a post parameter called "pin"
            //IFormCollection form = await context.Request.ReadFormAsync();
            //string submittedPin = form["PIN"];
            
            if(!String.IsNullOrEmpty(context.Token)){
                Guid refreshToken = Guid.Parse(context.Token);
                if(refreshToken != null){
                    ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();

                    OAuthSession oauthSession = dbContext.OAuthSessions.SingleOrDefault(oas => oas.RefreshToken == refreshToken);
                    OAuthClient oauthClient = context.OwinContext.Get<OAuthClient>(NicksApplicationOAuthProvider.OwinClientKey);

                    if (oauthSession != null && oauthClient != null && oauthSession.ClientId == oauthClient.Id && oauthClient.OrganizationId == oauthSession.OrganizationId && oauthSession.IsRefreshTokenValid(refreshToken, Startup.RefreshTokenTimeSpan))
                    {
                        ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
                        ApplicationUser user = await userManager.FindByIdAsync(oauthSession.UserId);
                        //Uncomment this and the closing brace to verify the PIN hash referenced above
                        //if (userManager.PasswordHasher.VerifyHashedPassword(user.PINHash,submittedPin) == PasswordVerificationResult.Success)
                        //{
                            context.OwinContext.Set<ApplicationUser>(NicksApplicationOAuthProvider.OwinUserKey, user);
                            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
                            IDictionary<string, string> properties = new Dictionary<string, string>{ { "userName", user.UserName } };
                            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties(properties));
                            ticket.Properties.IssuedUtc = DateTimeOffset.UtcNow;
                            ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan);
                            context.SetTicket(ticket);
                        //}
                    }
                }
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            // define o cabecalho da resposta do contexto do Owin com a permição de origem
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            // pega o Id do token pelo na requisição
            var hashedTokenId = HashHelper.GetHash(context.Token);

            // 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 refreshTokenDomain = DependecyConfig.Container.GetInstance<IRefreshTokenDomain>();
            // busca o token na base de dados pelo id
            var refreshToken = await refreshTokenDomain.ReadAsync(hashedTokenId, browser);

            // se o token for encontrado
            if (refreshToken != null)
            {
                // pega os dados do ticket para deserializar e gerar um novo ticket com 
                // as informações mapeadas do usuário que utiliza este token
                var ticketSerializer = new TicketSerializer();
                var ticket = ticketSerializer.Deserialize(refreshToken.ProtectedTicket);

                context.SetTicket(ticket);

                // remove o token da base de dados pois em nossa lógica, permitimos apenas 
                // um RefreshToken por usuário e aplicação cliente
                await refreshTokenDomain.DeleteAsync(hashedTokenId, browser);
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {

            using (var ctx = new ApplicationDbContext())
            {
                // Get the hash of our token
                var hash = Encryption.Hash(context.Token);

                // Find the refresh token by its hash
                var rt = (from r in ctx.RefreshTokens
                          where r.Id == hash
                          select r).SingleOrDefault();

                if (rt != null)
                {
                    // Get ticket from stored data
                    context.DeserializeTicket(rt.Ticket);
                    // Delete the token from the DB
                    ctx.RefreshTokens.Remove(rt);

                    // Save changes
                    await ctx.SaveChangesAsync();

                }
                
            }

        }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     var oAuthIdentity = new ClaimsIdentity();
     oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "jeremy"));
     var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
     context.SetTicket(ticket);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public override void Receive(AuthenticationTokenReceiveContext context)
 {
     string token;
     if (_refreshTokens.TryRemove(context.Token, out token))
     {
         context.DeserializeTicket(token);
     }
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     TicketResult result = Remove(context);
     if (result.Deleted)
     {
         context.SetTicket(result.Ticket);
     }
 }
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     TicketResult result = await RemoveAsync(context);
     if (result.Deleted)
     {
         context.SetTicket(result.Ticket);
     }
 }
 public override void Receive(AuthenticationTokenReceiveContext context)
 {
     string value;
     if (_codes.TryRemove(context.Token, out value))
     {
         context.DeserializeTicket(value);
     }
 }
 private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
 {
     string value;
     if (_authCodes.TryRemove(context.Token, out value))
     {
         context.DeserializeTicket(value);
     }
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     AuthenticationTicket ticket;
     if (RefreshTokens.TryRemove(context.Token, out ticket))
     {
         context.SetTicket(ticket);
     }
 }
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     AuthenticationTicket ticket;
     if (_refreshTokens.TryRemove(context.Token, out ticket))
     {
         context.SetTicket(ticket);
     }
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     //TODO: before generating a new ticket, validate the ticket has not expired, and has never
     //been used to generate a new ticket
     var token = new CustomTokenFormat().Unprotect(context.Token.Replace(" ", "+"));
     var ticket = AuthTicketBuilder.BuildTicket(token);
     context.SetTicket(ticket);
 }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            await Task.Run(() =>
            {
                context.DeserializeTicket(context.Token);
            });

            
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            AuthenticationTicket ticket;
            string header = context.OwinContext.Request.Headers["Authorization"];

            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                context.SetTicket(ticket);
            }
        }
 /// <summary>
 /// 移除RefreshToken,在客户端使用RefreshToken请求新的AccessToken的时候自动调用
 /// </summary>
 /// <param name="context"></param>
 public async override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     RefreshTokenInfo token = await _clientRefreshTokenStore.GetTokenInfo(context.Token);
     if (token == null)
     {
         return;
     }
     context.DeserializeTicket(token.ProtectedTicket);
     await _clientRefreshTokenStore.Remove(context.Token);
 }
        public void Receive(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);
            //var isUpdated = _usersRepository.IsRegisteredUserUpdated(context.Ticket.Identity.Claims.First(i => i.Type == ClaimTypes.NameIdentifier));

            /*f (isUpdated)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                context.Response.ReasonPhrase = Exceptions.UserDataChanged;
            }*/
        }
        public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var tokenValidator = new TokenValidator();

            ClaimsPrincipal principal = tokenValidator.Validate(context.Token, _options);

            context.SetTicket(new AuthenticationTicket((ClaimsIdentity)principal.Identity,
                new AuthenticationProperties()));

            return base.ReceiveAsync(context);
        }
 public override void Receive(AuthenticationTokenReceiveContext context)
 {
     var container = context.OwinContext.GetAutofacLifetimeScope();
     var membershipService = container.Resolve<IAuthorizationService>();
     var hashedTokenId = VaBank.Common.Security.Hash.Compute(context.Token);
     var token = membershipService.RevokeToken(new IdentityQuery<string>(hashedTokenId));
     if (token != null)
     {
         context.DeserializeTicket(token.Value);
     }
     base.Receive(context);
 }
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     //var hashedTokenId = CryptoAes.GetHash(context.Token);
     using (var authenticationTokenService = _dependencyResolver.GetService<IAuthenticationTokenFactory>())
     {
         var ticket = await authenticationTokenService.IssueAuthenticationTicketAsync(context.Token);
         if (ticket != null)
         {
             context.SetTicket(ticket);
         }
     }
 }
    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) {
      var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
      context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
      string hashedToken = PasswordHelper.HashToken(context.Token);

      var authenticationClient = new AuthenticationClient();
      var response = await authenticationClient.GetRefreshToken(new GetRefreshTokenRequest { HashedToken = hashedToken });
      if (response.RefreshToken != null) {
        context.DeserializeTicket(response.RefreshToken.ProtectedTicket);
        await authenticationClient.DeleteRefreshToken(new DeleteRefreshTokenRequest { HashedToken = hashedToken });
      }
    }
        public virtual void Receive(AuthenticationTokenReceiveContext context)
        {
            if (OnReceiveAsync != null && OnReceive == null)
            {
                throw new InvalidOperationException(Resources.Exception_AuthenticationTokenDoesNotProvideSyncMethods);
            }

            if (OnReceive != null)
            {
                OnReceive.Invoke(context);
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type" });

            AuthenticationTicket ticket;
            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                context.SetTicket(ticket);
            }
            //return Task.FromResult<object>(null);
        }
        public void Receive(AuthenticationTokenReceiveContext context)
        {
            var hashedTokenId = Helper.GetHash(context.Token);
            var appTokenService = mobSocialEngine.ActiveEngine.Resolve<IAppTokenService>();

            var appToken = appTokenService.FirstOrDefault(x => x.Guid == hashedTokenId);
            if (appToken != null)
            {
                //Get protectedTicket from refreshToken class
                context.DeserializeTicket(appToken.ProtectedTicket);
                appTokenService.Delete(appToken);
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            Guid token;
            if (Guid.TryParse(context.Token, out token))
            {
                AuthenticationTicket ticket;

                if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
                {
                    context.SetTicket(ticket);
                }
            }
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            var hashedTokenId = AuthorizationHelpers.GetHash(context.Token);

            var refreshToken = await _userRepository.FindRefreshTokenAsync(hashedTokenId);
            if (refreshToken != null)
            {
                context.DeserializeTicket(refreshToken.ProtectedTicket);
                await _userRepository.TryRemoveRefreshTokenAsync(hashedTokenId);
            }
        }