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 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 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);
 }
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     TicketResult result = await RemoveAsync(context);
     if (result.Deleted)
     {
         context.SetTicket(result.Ticket);
     }
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     TicketResult result = Remove(context);
     if (result.Deleted)
     {
         context.SetTicket(result.Ticket);
     }
 }
예제 #6
0
 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 void Receive(AuthenticationTokenReceiveContext context)
 {
     AuthenticationTicket ticket;
     if (RefreshTokens.TryRemove(context.Token, out ticket))
     {
         context.SetTicket(ticket);
     }
 }
 //<summary>
 //验证Token
 //</summary>
 //<param name="context">上下文</param>
 //<returns></returns>
 public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     var request = new OAuthRequestTokenContext(context.OwinContext, context.Token);
     var ticket = new AuthenticationTicket(new ClaimsIdentity(), new AuthenticationProperties()
     {
         IssuedUtc = DateTime.UtcNow.AddYears(-1),
         ExpiresUtc = DateTime.UtcNow.AddYears(-1)
     });
     if (request == null || request.Token.IsNullOrEmpty())
     {
         context.SetTicket(ticket);
     }
     //验证Token是否过期
     var vaild = true;//await _clientAuthorizationService.VaildOAuthClientSecretAsync();
     if (vaild)
     {
         context.SetTicket(ticket);
     }
 }
        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);
            }
        }
        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 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 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)
        {
            Guid token;
            if (Guid.TryParse(context.Token, out token))
            {
                AuthenticationTicket ticket;

                if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
                {
                    context.SetTicket(ticket);
                }
            }
        }
예제 #15
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            string clientId = context.OwinContext.Get<string>("as:client_id");
            string ticket = refreshTokenService.GetAuthenticationTicket(new Guid(context.Token), clientId);
            if (!string.IsNullOrEmpty(ticket) && !string.IsNullOrWhiteSpace(ticket))
            {
                context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(ticket)));

                var command = new ReduceRefreshTokenTTL()
                {
                    ClientId = clientId,
                    RefreshToken = Guid.Parse(context.Token),
                    AuthenticationTicket = ticket,
                    TTL = ttlChange
                };

                this.commandBus.Send(command);
            }
        }
        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 json = JArray.Parse(await response.Content.ReadAsStringAsync());
            var claims = new List<Claim>();

            foreach (var item in json)
            {
                claims.Add(new Claim(item["Type"].ToString(), item["Value"].ToString()));
            }

            context.SetTicket(new AuthenticationTicket(new ClaimsIdentity(claims, _authenticationType), new AuthenticationProperties()));
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {

            var oAuthIdentity = new ClaimsIdentity();
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "jeremy"));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "jeremy"));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.GivenName, "jeremy woo"));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties { AllowRefresh = true, IsPersistent = false, RedirectUri = "http://localhost", IssuedUtc = DateTime.Now, ExpiresUtc = DateTime.Now.AddMonths(1) });
            ticket.Identity.Label = "tetdemotoken";
            
            context.SetTicket(ticket);
            

            //var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

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

            //string hashedTokenId = "abc112233"; //Helper.GetHash(context.Token);

            //using (AuthRepository _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);
            //    }


            //    var oAuthIdentity = new ClaimsIdentity();
            //    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "jeremy"));
            //    var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            //    context.SetTicket(ticket);
            //}
        }
        private void SetAuthenticationTicket(AuthenticationTokenReceiveContext context, IEnumerable<Claim> claims)
        {
            var id = new ClaimsIdentity(
                            claims,
                            _options.AuthenticationType,
                            _options.NameClaimType,
                            _options.RoleClaimType);

            context.SetTicket(new AuthenticationTicket(id, new AuthenticationProperties()));
        }
        /// <summary>
        /// Authenticates a refresh token.
        /// </summary>
        /// <param name="context">The authentication context.</param>
        /// <returns/>
        public void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
        {
            this.options.Logger.Debug("Received refresh token");

            var clientId = context.OwinContext.GetOAuthContext().ClientId;
            var redirectUri = context.OwinContext.GetOAuthContext().RedirectUri;
            
            var tcs = new TaskCompletionSource<AuthenticationTicket>();
            Task.Run(
                async () =>
                {
                    try
                    {
                        var principal = await this.options.TokenManager.AuthenticateRefreshTokenAsync(clientId, context.Token, redirectUri);

                        if (principal.Identity.IsAuthenticated)
                        {
                            /* Override the validation parameters.
                             * This is because OWIN thinks the principal.Identity.Name should 
                             * be the same as the client_id from ValidateClientAuthentication method,
                             * but we need to use the user id in Sentinel.
                             */
                            var props = new AuthenticationProperties();
                            props.Dictionary.Add("client_id", principal.Identity.Claims.First(x => x.Type == ClaimType.Client).Value);
                            props.RedirectUri = redirectUri;
                            props.ExpiresUtc = DateTimeOffset.UtcNow.Add(this.options.RefreshTokenLifetime);

                            // TODO: Use UserManager to get new data

                            tcs.SetResult(new AuthenticationTicket(principal.Identity.AsClaimsIdentity(), props));
                        }
                        else
                        {
                            tcs.SetResult(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                }).ConfigureAwait(false);

            var result = tcs.Task.Result;

            if (result != null)
            {
                context.SetTicket(result);
            }

            this.options.Logger.Debug("Finished processing refresh token");
        }
        /// <summary>
        /// Authenticates an access token.
        /// </summary>
        /// <param name="context">The authentication context.</param>
        /// <returns/>
        private void ReceiveAccessToken(AuthenticationTokenReceiveContext context)
        {
            this.options.Logger.DebugFormat("Received access token");

            var tcs = new TaskCompletionSource<AuthenticationTicket>();
            Task.Run(
                async () =>
                {
                    try
                    {
                        var principal = await this.options.TokenManager.AuthenticateAccessTokenAsync(context.Token);

                        if (principal.Identity.IsAuthenticated)
                        {
                            var props = new AuthenticationProperties
                                            {
                                                ExpiresUtc = DateTimeOffset.UtcNow.Add(this.options.AccessTokenLifetime)
                                            };

                            /* Override the validation parameters.
                             * This is because OWIN thinks the principal.Identity.Name should 
                             * be the same as the client_id from ValidateClientAuthentication method,
                             * but we need to use the user id in Sentinel.
                             */
                            if (principal.Identity.HasClaim(x => x.Type == ClaimType.Client))
                            {
                                props.Dictionary.Add("client_id", principal.Identity.Claims.First(x => x.Type == ClaimType.Client).Value);
                            }

                            tcs.SetResult(new AuthenticationTicket(principal.Identity.AsClaimsIdentity(), props));
                        }
                        else
                        {
                            tcs.SetResult(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                }).ConfigureAwait(false);

            var result = tcs.Task.Result;

            if (result != null)
            {
                context.SetTicket(result);
            }

            this.options.Logger.Debug("Finished processing access token");
        }
        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 = new RefreshTokenDomain();

            // 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);
            }
        }