コード例 #1
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            Guid userid = NullHandlers.NGUID(context.Ticket.Properties.Dictionary["as:user_id"]);

            if (userid == Guid.Empty)
            {
                return;
            }

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

            var refreshTokenLifeTime = 30;

            var token = new RefreshToken()
            {
                Id         = Infrastructure.Encryption.GetHash(refreshTokenId),
                UserId     = userid,
                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 UnitOfWork.RefreshTokenStore.CreateAsync(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }
コード例 #2
0
        public async Task <IHttpActionResult> Post([FromBody] Models.RoleViewModel value)
        {
            Role _role = null;

            if (NullHandlers.NGUID(value.Id) != Guid.Empty)
            {
                _role = await UnitOfWork.RoleStore.FindByIdAsync(value.Id);
            }
            if (_role == null)
            {
                _role = new Role();
            }
            _role.Name        = value.RoleName;
            _role.Description = value.RoleDescription;
            UnitOfWork.BeginWork();
            if (_role.Id == Guid.Empty)
            {
                await UnitOfWork.RoleStore.CreateAsync(_role);
            }
            else
            {
                await UnitOfWork.RoleStore.UpdateAsync(_role);
            }
            foreach (Models.ApiViewModel _assignedApi in value.AssignedApis)
            {
                if (_assignedApi.Id == Guid.Empty)
                {
                    RoleApiPath _newPath = new RoleApiPath()
                    {
                        RoleId = _role.Id, ActionPath = _assignedApi.Path, ActionMethod = _assignedApi.HttpMethod
                    };
                    await UnitOfWork.RoleStore.CreateRoleApiPathAsync(_newPath);
                }
            }
            foreach (Models.ApiViewModel _availableApi in value.AvailableApis)
            {
                if (_availableApi.Id != Guid.Empty)
                {
                    await UnitOfWork.RoleStore.DeleteRoleApiPathAsync(_availableApi.Id);;
                }
            }
            foreach (Models.ClientPathViewModel _assignedClientPath in value.AssignedClientPaths)
            {
                if (_assignedClientPath.Id == Guid.Empty)
                {
                }
            }
            foreach (Models.ClientPathViewModel _availableClientPath in value.AvailableClientPaths)
            {
                if (_availableClientPath.Id != Guid.Empty)
                {
                }
            }
            UnitOfWork.CommitWork();
            return(Ok());
        }
コード例 #3
0
        public async Task <IHttpActionResult> GetUser(string Id)
        {
            try
            {
                User _user = await _userFactory.Build(NullHandlers.NGUID(Id));

                return(Ok(_user));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
コード例 #4
0
        public async Task <IHttpActionResult> Get(string id)
        {
            Guid _roleId = NullHandlers.NGUID(id);
            Role _role   = null;

            if (_roleId != Guid.Empty)
            {
                _role = await UnitOfWork.RoleStore.FindByIdAsync(_roleId);
            }
            if (_role == null)
            {
                _role = new Role();
            }
            List <Models.ApiViewModel>        _assignedApis         = new List <Models.ApiViewModel>();
            List <Models.ApiViewModel>        _availableApis        = new List <Models.ApiViewModel>();
            List <Models.ClientPathViewModel> _availableClientPaths = new List <Models.ClientPathViewModel>();
            List <Models.ClientPathViewModel> _assignedClientPaths  = new List <Models.ClientPathViewModel>();

            foreach (RoleApiPath _apiPath in await UnitOfWork.RoleStore.ListRoleApiPathsAsync(_role.Id))
            {
                _assignedApis.Add(new Models.ApiViewModel()
                {
                    Id = _apiPath.Id, Path = _apiPath.ActionPath, HttpMethod = _apiPath.ActionMethod
                });
            }
            System.Collections.ObjectModel.Collection <System.Web.Http.Description.ApiDescription> _apis = GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions;
            foreach (System.Web.Http.Description.ApiDescription _api in _apis)
            {
                if (_api.ActionDescriptor.GetFilterPipeline().Where(f => f.Instance is Attributes.AuthorizeUserAttribute).Any())
                {
                    if (!(_assignedApis.Where(f => f.Path == _api.RelativePath && f.HttpMethod == _api.HttpMethod.ToString()).Any()))
                    {
                        _availableApis.Add(new Models.ApiViewModel()
                        {
                            Path = _api.RelativePath, HttpMethod = _api.HttpMethod.ToString()
                        });
                    }
                }
            }
            return(Ok(new Models.RoleViewModel()
            {
                Id = _role.Id, RoleName = _role.Name, RoleDescription = _role.Description, AssignedApis = _assignedApis, AvailableApis = _availableApis, AvailableClientPaths = _availableClientPaths, AssignedClientPaths = _assignedClientPaths
            }));
        }
コード例 #5
0
ファイル: CustomOAuthProvider.cs プロジェクト: mkeeton/ISS
        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);
        }