Ejemplo n.º 1
0
        public async Task <DiscoveryInformation> Execute()
        {
            var result = new DiscoveryInformation();

            // Returns only the exposed scopes
            var scopes = await _scopeRepository.GetAllAsync();

            var scopeSupportedNames = new string[0];

            if (scopes != null ||
                scopes.Any())
            {
                scopeSupportedNames = scopes.Where(s => s.IsExposed).Select(s => s.Name).ToArray();
            }

            var responseTypesSupported = GetSupportedResponseTypes(Constants.Supported.SupportedAuthorizationFlows);

            var grantTypesSupported      = GetSupportedGrantTypes();
            var tokenAuthMethodSupported = GetSupportedTokenEndPointAuthMethods();

            result.ClaimsParameterSupported      = true;
            result.RequestParameterSupported     = true;
            result.RequestUriParameterSupported  = true;
            result.RequireRequestUriRegistration = true;
            result.ClaimsSupported                  = (await _claimRepository.GetAllAsync()).Select(c => c.Code).ToArray();
            result.ScopesSupported                  = scopeSupportedNames;
            result.ResponseTypesSupported           = responseTypesSupported;
            result.ResponseModesSupported           = Constants.Supported.SupportedResponseModes.ToArray();
            result.GrantTypesSupported              = grantTypesSupported;
            result.SubjectTypesSupported            = Constants.Supported.SupportedSubjectTypes.ToArray();
            result.TokenEndpointAuthMethodSupported = tokenAuthMethodSupported;
            result.IdTokenSigningAlgValuesSupported = Constants.Supported.SupportedJwsAlgs.ToArray();

            return(result);
        }
Ejemplo 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);
        }
Ejemplo n.º 4
0
        public async Task <bool> Execute(UpdateResourceOwnerClaimsParameter request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var resourceOwner = await _resourceOwnerRepository.GetAsync(request.Login);

            if (resourceOwner == null)
            {
                throw new IdentityServerManagerException(ErrorCodes.InvalidParameterCode, string.Format(ErrorDescriptions.TheResourceOwnerDoesntExist, request.Login));
            }

            resourceOwner.UpdateDateTime = DateTime.UtcNow;
            var claims         = new List <Claim>();
            var existingClaims = await _claimRepository.GetAllAsync();

            if (existingClaims != null && existingClaims.Any() && request.Claims != null && request.Claims.Any())
            {
                foreach (var claim in request.Claims)
                {
                    var cl = existingClaims.FirstOrDefault(c => c.Code == claim.Key);
                    if (cl == null)
                    {
                        continue;
                    }

                    claims.Add(new Claim(claim.Key, claim.Value));
                }
            }

            resourceOwner.Claims = claims;
            Claim updatedClaim, subjectClaim;

            if (((updatedClaim = resourceOwner.Claims.FirstOrDefault(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt)) != null))
            {
                resourceOwner.Claims.Remove(updatedClaim);
            }

            if (((subjectClaim = resourceOwner.Claims.FirstOrDefault(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject)) != null))
            {
                resourceOwner.Claims.Remove(subjectClaim);
            }

            resourceOwner.Claims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, request.Login));
            resourceOwner.Claims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()));
            var result = await _resourceOwnerRepository.UpdateAsync(resourceOwner);

            if (!result)
            {
                throw new IdentityServerManagerException(ErrorCodes.InternalErrorCode, ErrorDescriptions.TheClaimsCannotBeUpdated);
            }

            return(true);
        }
Ejemplo n.º 5
0
        public async Task <bool> Execute(string subject, IEnumerable <ClaimAggregate> claims)
        {
            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }

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

            var resourceOwner = await _resourceOwnerRepository.GetAsync(subject);

            if (resourceOwner == null)
            {
                throw new IdentityServerException(Errors.ErrorCodes.InternalError, Errors.ErrorDescriptions.TheRoDoesntExist);
            }

            var supportedClaims = await _claimRepository.GetAllAsync();

            claims = claims.Where(c => supportedClaims.Any(sp => sp.Code == c.Code && !Jwt.Constants.NotEditableResourceOwnerClaimNames.Contains(c.Code)));
            var claimsToBeRemoved = resourceOwner.Claims
                                    .Where(cl => claims.Any(c => c.Code == cl.Type))
                                    .Select(cl => resourceOwner.Claims.IndexOf(cl))
                                    .OrderByDescending(p => p)
                                    .ToList();

            foreach (var index in claimsToBeRemoved)
            {
                resourceOwner.Claims.RemoveAt(index);
            }

            foreach (var claim in claims)
            {
                if (string.IsNullOrWhiteSpace(claim.Value))
                {
                    continue;
                }

                resourceOwner.Claims.Add(new Claim(claim.Code, claim.Value));
            }

            Claim updatedClaim;

            if (((updatedClaim = resourceOwner.Claims.FirstOrDefault(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt)) != null))
            {
                resourceOwner.Claims.Remove(updatedClaim);
            }

            resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()));
            return(await _resourceOwnerRepository.UpdateAsync(resourceOwner));
        }
        public async Task <IEnumerable <ClaimDTO> > Handle(GetAllClaimsQuery command, CancellationToken cancellationToken)
        {
            var claims = await _claimRepository.GetAllAsync();

            return(claims.Select(claim => new ClaimDTO
            {
                ClaimId = claim.ClaimId,
                Date = claim.Date,
                UserId = claim.UserId,
                Description = claim.Description,
                Incidence = claim.Incidence,
                DamagedItem = claim.DamagedItem,
                Status = nameof(claim.Status),
                Street = claim.Street,
                City = claim.City,
                Country = claim.Country
            }));
        }
        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);
        }
Ejemplo n.º 8
0
        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);
        }
 public Task <IEnumerable <ClaimAggregate> > Execute()
 {
     return(_claimRepository.GetAllAsync());
 }