public async Task <ResourceOwner> Execute(LocalAuthenticateParameter parameter, string imagePath, string hostUrl)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (string.IsNullOrWhiteSpace(parameter.Xml))
            {
                throw new ArgumentNullException(nameof(parameter.Xml));
            }

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(parameter.Xml);
            CheckXmlWellFormed(xmlDocument);
            var resourceOwner         = ExtractResourceOwner(xmlDocument, imagePath, hostUrl);
            var existingResourceowner = await _resourceOwnerRepository.GetAsync(resourceOwner.Id);

            if (existingResourceowner == null)
            {
                await _resourceOwnerRepository.InsertAsync(resourceOwner);
            }

            return(resourceOwner);
        }
Esempio n. 2
0
        public async Task <ExternalOpenIdAuthenticationResult> Execute(
            List <Claim> claims,
            AuthorizationParameter authorizationParameter,
            string code)
        {
            // 1. Check parameters.
            if (claims == null || !claims.Any())
            {
                throw new ArgumentNullException(nameof(claims));
            }

            if (authorizationParameter == null)
            {
                throw new ArgumentNullException(nameof(authorizationParameter));
            }

            if (string.IsNullOrWhiteSpace(code))
            {
                throw new ArgumentNullException(nameof(code));
            }

            // 2. Subject cannot be extracted.
            var subject = claims.GetSubject();

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode,
                                                  ErrorDescriptions.NoSubjectCanBeExtracted);
            }

            // 3. Create the resource owner if needed.
            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(subject);

            if (resourceOwner == null)
            {
                var standardClaims = await _claimRepository.GetAllAsync();

                resourceOwner = new ResourceOwner
                {
                    Id                      = subject,
                    IsLocalAccount          = false,
                    TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                    Claims                  = claims.Where(c => standardClaims.Any(sc => sc == c.Type)).ToList()
                };
                if (!resourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
                {
                    resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject));
                }

                await _resourceOwnerRepository.InsertAsync(resourceOwner);
            }
            return(new ExternalOpenIdAuthenticationResult
            {
                ActionResult = await _authenticateHelper.ProcessRedirection(authorizationParameter,
                                                                            code,
                                                                            "subject",
                                                                            claims),
                Claims = resourceOwner.Claims
            });
        }
        public async Task <bool> Execute(AddUserParameter addUserParameter)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            if (string.IsNullOrEmpty(addUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Login));
            }

            if (string.IsNullOrWhiteSpace(addUserParameter.Password))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Password));
            }

            if (await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(addUserParameter.Login,
                                                                                       addUserParameter.Password) != null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var newClaims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login)
            };
            var newResourceOwner = new ResourceOwner
            {
                Id     = addUserParameter.Login,
                Claims = newClaims,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                IsLocalAccount          = true,
                Password = _authenticateResourceOwnerService.GetHashedPassword(addUserParameter.Password)
            };
            var claims = (await _claimRepository.GetAllAsync()).Select(c => c.Code);

            if (addUserParameter.Claims != null)
            {
                foreach (var claim in addUserParameter.Claims.Where(c => claims.Contains(c.Type)))
                {
                    newResourceOwner.Claims.Add(claim);
                }
            }

            if (!newResourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
            {
                newResourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login));
            }

            await _resourceOwnerRepository.InsertAsync(newResourceOwner);

            return(true);
        }
        public async Task Execute(AddUserParameter addUserParameter)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            if (string.IsNullOrEmpty(addUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Login));
            }

            if (string.IsNullOrWhiteSpace(addUserParameter.Password))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Password));
            }

            if (await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(addUserParameter.Login,
                                                                                       addUserParameter.Password) != null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var claims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login)
            };
            var newResourceOwner = new ResourceOwner
            {
                Id     = addUserParameter.Login,
                Claims = claims,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                IsLocalAccount          = true,
                Password = _authenticateResourceOwnerService.GetHashedPassword(addUserParameter.Password)
            };
            await _resourceOwnerRepository.InsertAsync(newResourceOwner);
        }
        public async Task <IEnumerable <Claim> > Execute(ClaimsPrincipal claimsPrincipal)
        {
            // 1. Check parameters.
            if (claimsPrincipal == null)
            {
                throw new ArgumentNullException(nameof(claimsPrincipal));
            }

            // 2. Check the user is authenticated.
            if (claimsPrincipal.Identity == null ||
                !claimsPrincipal.Identity.IsAuthenticated ||
                !(claimsPrincipal.Identity is ClaimsIdentity))
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheUserNeedsToBeAuthenticated);
            }

            // 3. Check the subject exists.
            var subject = claimsPrincipal.GetSubject();

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoCannotBeCreated);
            }

            // 4. If a user already exists with the same subject then ignore.
            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(subject);

            if (resourceOwner != null)
            {
                return(resourceOwner.Claims);
            }

            // 5. Insert the resource owner.
            var clearPassword = Guid.NewGuid().ToString();

            resourceOwner = new ResourceOwner
            {
                Id                      = subject,
                IsLocalAccount          = false,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                Claims                  = new List <Claim>(),
                Password                = _authenticateResourceOwnerService.GetHashedPassword(clearPassword)
            };
            var claims = await _claimRepository.GetAllAsync();

            foreach (var claim in claimsPrincipal.Claims.Where(c => claims.Contains(c.Type)))
            {
                resourceOwner.Claims.Add(claim);
            }

            if (!resourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
            {
                resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject));
            }

            await _resourceOwnerRepository.InsertAsync(resourceOwner);

            return(resourceOwner.Claims);
        }
        public async Task <string> Execute(AddUserParameter addUserParameter, string issuer = null)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            var subject = await _subjectBuilder.BuildSubject().ConfigureAwait(false);

            // 1. Check the resource owner already exists.
            if (await _resourceOwnerRepository.GetAsync(subject) != null)
            {
                throw new IdentityServerException(Errors.ErrorCodes.UnhandledExceptionCode, Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var newClaims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };

            // 2. Populate the claims.
            var existedClaims = await _claimRepository.GetAllAsync().ConfigureAwait(false);

            if (addUserParameter.Claims != null)
            {
                foreach (var claim in addUserParameter.Claims)
                {
                    if (!newClaims.Any(nc => nc.Type == claim.Type) && existedClaims.Any(c => c.Code == claim.Type))
                    {
                        newClaims.Add(claim);
                    }
                }
            }

            var isFilterValid    = true;
            var userFilterResult = await _accountFilter.Check(newClaims).ConfigureAwait(false);

            if (!userFilterResult.IsValid)
            {
                isFilterValid = false;
                foreach (var ruleResult in userFilterResult.AccountFilterRules)
                {
                    if (!ruleResult.IsValid)
                    {
                        _openidEventSource.Failure($"the filter rule '{ruleResult.RuleName}' failed");
                        foreach (var errorMessage in ruleResult.ErrorMessages)
                        {
                            _openidEventSource.Failure(errorMessage);
                        }
                    }
                }
            }

            if (!isFilterValid)
            {
                throw new IdentityServerException(Errors.ErrorCodes.InternalError, Errors.ErrorDescriptions.TheUserIsNotAuthorized);
            }

            // 3. Add the scim resource.
            if (_userClaimsEnricherLst != null)
            {
                foreach (var userClaimsEnricher in _userClaimsEnricherLst)
                {
                    await userClaimsEnricher.Enrich(newClaims).ConfigureAwait(false);
                }
            }

            // 4. Add the resource owner.
            var newResourceOwner = new ResourceOwner
            {
                Id             = subject,
                Claims         = newClaims,
                CreateDateTime = DateTime.UtcNow,
                UpdateDateTime = DateTime.UtcNow,
                IsBlocked      = false
            };

            if (!await _resourceOwnerRepository.InsertAsync(newResourceOwner).ConfigureAwait(false))
            {
                throw new IdentityServerException(Errors.ErrorCodes.UnhandledExceptionCode, Errors.ErrorDescriptions.TheResourceOwnerCannotBeAdded);
            }

            // 5. Add credentials.
            if (addUserParameter.Credentials != null)
            {
                foreach (var c in addUserParameter.Credentials)
                {
                    c.UserId = subject;
                }

                await _addUserCredentialsOperation.Execute(addUserParameter.Credentials).ConfigureAwait(false);
            }

            // 6. Link to a profile.
            if (!string.IsNullOrWhiteSpace(issuer))
            {
                await _linkProfileAction.Execute(subject, addUserParameter.ExternalLogin, issuer).ConfigureAwait(false);
            }

            _openidEventSource.AddResourceOwner(newResourceOwner.Id);
            return(subject);
        }