public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = "NONE";

            List <ClientAllowedOrigin> _allowedOrigins;

            _allowedOrigins = await UnitOfWork.ClientStore.ListAllowedOrigins(new Guid());

            string _originPath = NullHandlers.NES(context.Request.Headers["Origin"]);

            if (_originPath == "")
            {
                allowedOrigin = "*";
            }
            else
            {
                string _originCompare = _originPath.ToLower().Trim();
                if (_originCompare.LastIndexOf("/") != (_originCompare.Length - 1))
                {
                    _originCompare += "/";
                }
                foreach (ClientAllowedOrigin _origin in _allowedOrigins)
                {
                    string _allowedCompare = _origin.AllowedURL.ToLower().Trim();
                    if ((_allowedCompare.LastIndexOf("/") != (_allowedCompare.Length - 1)) && (_allowedCompare != "*"))
                    {
                        _allowedCompare += "/";
                    }
                    if ((_origin.AllowedURL.ToLower().Trim() == "*") || (_origin.AllowedURL.ToLower().Trim() == _originCompare))
                    {
                        allowedOrigin = _originPath;
                        break;
                    }
                }
            }
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            string hashedTokenId = Infrastructure.Encryption.GetHash(context.Token);

            var refreshToken = await UnitOfWork.RefreshTokenStore.FindById(hashedTokenId);

            if (refreshToken != null)
            {
                //Get protectedTicket from refreshToken class
                context.DeserializeTicket(refreshToken.ProtectedTicket);

                var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
                var currentClient  = context.OwinContext.Get <string>("as:current_client_id");

                if (originalClient.ToLower().Trim() == currentClient.ToLower().Trim())
                {
                    var result = await UnitOfWork.RefreshTokenStore.DeleteAsync(hashedTokenId);
                }
            }
        }
Exemple #2
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            Client client     = context.OwinContext.Get <Client>("as:requested_client");
            string _authToken = String.Empty;

            if (client != null)
            {
                foreach (var _header in context.OwinContext.Request.Headers)
                {
                    if (_header.Key.ToLower() == "authorization")
                    {
                        if (_header.Value.Length > 0)
                        {
                            _authToken = _header.Value[0];
                            break;
                        }
                    }
                }
            }
            if (_authToken.IndexOf("Bearer ", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                _authToken = _authToken.Substring(7, _authToken.Length - 7);
            }
            var allowedOrigin = "NONE";

            List <ClientAllowedOrigin> _allowedOrigins;

            if (!(client == null))
            {
                _allowedOrigins = client.AllowedOrigins;
            }
            else
            {
                _allowedOrigins = await UnitOfWork.ClientStore.ListAllowedOrigins(new Guid());
            }

            string _originPath = NullHandlers.NES(context.Request.Headers["Origin"]);

            if (_originPath == "")
            {
                allowedOrigin = "*";
            }
            else
            {
                string _originCompare = _originPath.ToLower().Trim();
                if (_originCompare.LastIndexOf("/") != (_originCompare.Length - 1))
                {
                    _originCompare += "/";
                }
                foreach (ClientAllowedOrigin _origin in _allowedOrigins)
                {
                    string _allowedCompare = _origin.AllowedURL.ToLower().Trim();
                    if ((_allowedCompare.LastIndexOf("/") != (_allowedCompare.Length - 1)) && (_allowedCompare != "*"))
                    {
                        _allowedCompare += "/";
                    }
                    if ((_origin.AllowedURL.ToLower().Trim() == "*") || (_origin.AllowedURL.ToLower().Trim() == _originCompare))
                    {
                        allowedOrigin = _originPath;
                        Client _sourceClient = await UnitOfWork.ClientStore.FindByURL(_allowedCompare);

                        if (_sourceClient != null)
                        {
                            context.OwinContext.Set <Client>("as:source_client", _sourceClient);
                        }
                        break;
                    }
                }
            }

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

            AuthenticationProperties prop          = new AuthenticationProperties();
            ClaimsIdentity           oAuthIdentity = null;
            User user = null;

            //If the passed authentication token is empty then attempt to load the user from the username and password and then insert it into the AuthenticationTicket.
            //If the authentication token is not empty the ndecode the token and take the user identity from the token and place it in the new token for the remote resource.

            if (_authToken == "")
            {
                user = await UserManager.FindAsync(context.UserName, context.Password);

                if ((user == null) || ((user.Locked == true) && (user.LockedUntil.HasValue == true) && (user.LockedUntil.Value > DateTime.Now)))
                {
                    if (user == null)
                    {
                        user = await UnitOfWork.UserStore.FindByEmailAsync(context.UserName);

                        if (user != null)
                        {
                            if ((user.Locked == true) && (user.LockedUntil.HasValue == true) &&
                                (user.LockedUntil.Value > DateTime.Now))
                            {
                                user.FailedLoginCount = 0;
                                context.SetError("invalid_grant", "This user account is temporarily locked. Please try again later.");
                            }
                            else
                            {
                                user.FailedLoginCount += 1;
                                context.SetError("invalid_grant", "The user name or password is incorrect.");
                            }
                        }
                        else
                        {
                            context.SetError("invalid_grant", "The user name or password is incorrect.");
                        }
                    }

                    if (user != null)
                    {
                        if (user.FailedLoginCount >= 3)
                        {
                            user.Locked      = true;
                            user.LockedUntil = DateTime.Now.AddMinutes(10);
                        }
                        await UnitOfWork.UserStore.UpdateAsync(user);
                    }
                    return;
                }
                else
                {
                    //Clear all currently stored expired refresh tokens.
                    await UnitOfWork.RefreshTokenStore.ClearExpiredAsync();
                }
                if (user.Locked == true)
                {
                    user.FailedLoginCount = 0;
                    user.Locked           = false;
                    user.LockedUntil      = null;
                    await UnitOfWork.UserStore.UpdateAsync(user);
                }
                oAuthIdentity = await UserManager.GenerateUserIdentityAsync(user, "JWT");

                oAuthIdentity.AddClaims(UnitOfWork.ClaimStore.GetClaims(user));

                prop.Dictionary.Add("as:user_id", NullHandlers.NES(user.Id));
            }
            else
            {
                Guid _userId = new Guid();
                AuthenticationTicket _authTicket = context.Options.AccessTokenFormat.Unprotect(_authToken);
                ClaimsIdentity       _ident      = _authTicket.Identity;
                foreach (Claim _claim in _ident.Claims)
                {
                    foreach (var _prop in _claim.Properties)
                    {
                        if (_prop.Value == "nameid")
                        {
                            _userId = NullHandlers.NGUID(_claim.Value);
                            break;
                        }
                    }
                    if (_userId != Guid.Empty)
                    {
                        break;
                    }
                }
                if ((_userId == Guid.Empty) || (_ident == null))
                {
                    throw new Exception("Invalid Authentication Token");
                }
                oAuthIdentity = _ident;
                prop.Dictionary.Add("as:user_id", NullHandlers.NES(_userId));
            }

            prop.Dictionary.Add("as:issuer", ConfigurationManager.AppSettings["as:IssuerId"]);

            if (client == null)
            {
                prop.Dictionary.Add("as:client_id", ConfigurationManager.AppSettings["as:AudienceId"]);
                prop.Dictionary.Add("as:client_secret", ConfigurationManager.AppSettings["as:AudienceSecret"]);
            }
            else
            {
                prop.Dictionary.Add("as:client_id", client.ClientId);
                prop.Dictionary.Add("as:client_secret", client.Secret);
            }
            var ticket = new AuthenticationTicket(oAuthIdentity, prop);

            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            Client client = context.OwinContext.Get <Client>("as:requested_client");

            var allowedOrigin = "NONE";

            List <ClientAllowedOrigin> _allowedOrigins;

            if (!(client == null))
            {
                _allowedOrigins = client.AllowedOrigins;
            }
            else
            {
                _allowedOrigins = await UnitOfWork.ClientStore.ListAllowedOrigins(new Guid());
            }
            string _originPath = NullHandlers.NES(context.Request.Headers["Origin"]);

            if (_originPath == "")
            {
                allowedOrigin = "*";
            }
            else
            {
                string _originCompare = _originPath.ToLower().Trim();
                if (_originCompare.LastIndexOf("/") != (_originCompare.Length - 1))
                {
                    _originCompare += "/";
                }
                foreach (ClientAllowedOrigin _origin in _allowedOrigins)
                {
                    string _allowedCompare = _origin.AllowedURL.ToLower().Trim();
                    if ((_allowedCompare.LastIndexOf("/") != (_allowedCompare.Length - 1)) && (_allowedCompare != "*"))
                    {
                        _allowedCompare += "/";
                    }
                    if ((_origin.AllowedURL.ToLower().Trim() == "*") || (_origin.AllowedURL.ToLower().Trim() == _originCompare))
                    {
                        allowedOrigin = _originPath;
                        break;
                    }
                }
            }

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

            User user = await UnitOfWork.UserManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            //if (!user.EmailConfirmed)
            //{
            //  context.SetError("invalid_grant", "User did not confirm email.");
            //  return;
            //}

            ClaimsIdentity oAuthIdentity = await UnitOfWork.UserManager.GenerateUserIdentityAsync(user, "JWT");

            oAuthIdentity.AddClaims(UnitOfWork.ClaimStore.GetClaims(user));
            //oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            AuthenticationProperties prop = new AuthenticationProperties();

            prop.Dictionary.Add("as:issuer", "http://localhost:50378");
            prop.Dictionary.Add("as:user_id", NullHandlers.NES(user.Id));
            prop.Dictionary.Add("as:client_id", ConfigurationManager.AppSettings["as:AudienceId"]);
            prop.Dictionary.Add("as:client_secret", ConfigurationManager.AppSettings["as:AudienceSecret"]);
            var ticket = new AuthenticationTicket(oAuthIdentity, prop);

            context.Validated(ticket);
        }