public Task <ResourceSet> Execute(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            return(_resourceSetRepository.Get(id));
        }
Пример #2
0
        public async Task <string> Execute(AddPolicyParameter addPolicyParameter)
        {
            var json = addPolicyParameter == null ? string.Empty : JsonConvert.SerializeObject(addPolicyParameter);

            _umaServerEventSource.StartAddingAuthorizationPolicy(json);
            if (addPolicyParameter == null)
            {
                throw new ArgumentNullException(nameof(addPolicyParameter));
            }

            if (addPolicyParameter.ResourceSetIds == null || !addPolicyParameter.ResourceSetIds.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode,
                                           string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPolicyParameterNames.ResourceSetIds));
            }

            foreach (var resourceSetId in addPolicyParameter.ResourceSetIds)
            {
                var resourceSet = await _repositoryExceptionHelper.HandleException(
                    string.Format(ErrorDescriptions.TheResourceSetCannotBeRetrieved, resourceSetId),
                    () => _resourceSetRepository.Get(resourceSetId));

                if (resourceSet == null)
                {
                    throw new BaseUmaException(ErrorCodes.InvalidResourceSetId, string.Format(ErrorDescriptions.TheResourceSetDoesntExist, resourceSetId));
                }

                if (addPolicyParameter.Scopes.Any(r => !resourceSet.Scopes.Contains(r)))
                {
                    throw new BaseUmaException(ErrorCodes.InvalidScope, ErrorDescriptions.OneOrMoreScopesDontBelongToAResourceSet);
                }
            }

            // Insert policy
            var policy = new Policy
            {
                Id             = Guid.NewGuid().ToString(),
                ClientIds      = addPolicyParameter.ClientIdsAllowed,
                ResourceSetIds = addPolicyParameter.ResourceSetIds,
                IsResourceOwnerConsentNeeded = addPolicyParameter.IsResourceOwnerConsentNeeded,
                Script = addPolicyParameter.Script,
                Scopes = addPolicyParameter.Scopes,
                Claims = addPolicyParameter.Claims == null ? new List <Claim>() : addPolicyParameter.Claims.Select(c => new Claim
                {
                    Type  = c.Type,
                    Value = c.Value
                }).ToList()
            };

            await _repositoryExceptionHelper.HandleException(ErrorDescriptions.ThePolicyCannotBeInserted, () => _policyRepository.Add(policy));

            _umaServerEventSource.FinishToAddAuthorizationPolicy(JsonConvert.SerializeObject(policy));
            return(policy.Id);
        }
Пример #3
0
        public async Task <bool> Execute(UpdatePolicyParameter updatePolicyParameter)
        {
            if (updatePolicyParameter == null)
            {
                throw new ArgumentNullException(nameof(updatePolicyParameter));
            }

            if (string.IsNullOrWhiteSpace(updatePolicyParameter.PolicyId))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, "id"));
            }

            _umaServerEventSource.StartUpdateAuthorizationPolicy(JsonConvert.SerializeObject(updatePolicyParameter));
            var policy = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeRetrieved, updatePolicyParameter.PolicyId),
                () => _policyRepository.Get(updatePolicyParameter.PolicyId));

            if (policy == null)
            {
                return(false);
            }

            foreach (var resourceSetId in policy.ResourceSetIds)
            {
                var resourceSet = await _resourceSetRepository.Get(resourceSetId).ConfigureAwait(false);

                if (updatePolicyParameter.Scopes.Any(r => !resourceSet.Scopes.Contains(r)))
                {
                    throw new BaseUmaException(ErrorCodes.InvalidScope, ErrorDescriptions.OneOrMoreScopesDontBelongToAResourceSet);
                }
            }

            policy.Scopes = updatePolicyParameter.Scopes;
            policy.IsResourceOwnerConsentNeeded = updatePolicyParameter.IsResourceOwnerConsentNeeded;
            policy.Claims = new List <Claim>();
            policy.Script = updatePolicyParameter.Script;
            if (updatePolicyParameter.Claims != null)
            {
                policy.Claims = updatePolicyParameter.Claims.Select(c => new Claim
                {
                    Type  = c.Type,
                    Value = c.Value
                }).ToList();
            }

            var result = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeUpdated, updatePolicyParameter.PolicyId),
                () => _policyRepository.Update(policy));

            _umaServerEventSource.FinishUpdateAuhthorizationPolicy(JsonConvert.SerializeObject(updatePolicyParameter));
            return(result);
        }
        public async Task <bool> Execute(AddResourceSetParameter addResourceSetParameter)
        {
            if (addResourceSetParameter == null)
            {
                throw new ArgumentNullException(nameof(addResourceSetParameter));
            }

            if (string.IsNullOrWhiteSpace(addResourceSetParameter.PolicyId))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddResourceSetParameterNames.PolicyId));
            }

            if (addResourceSetParameter.ResourceSets == null ||
                !addResourceSetParameter.ResourceSets.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddResourceSetParameterNames.ResourceSet));
            }

            _umaServerEventSource.StartAddResourceToAuthorizationPolicy(addResourceSetParameter.PolicyId, string.Join(",", addResourceSetParameter.ResourceSets));
            var policy = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeRetrieved, addResourceSetParameter.PolicyId),
                () => _policyRepository.Get(addResourceSetParameter.PolicyId));

            if (policy == null)
            {
                return(false);
            }

            foreach (var resourceSetId in addResourceSetParameter.ResourceSets)
            {
                var resourceSet = await _repositoryExceptionHelper.HandleException(
                    string.Format(ErrorDescriptions.TheResourceSetCannotBeRetrieved, resourceSetId),
                    () => _resourceSetRepository.Get(resourceSetId));

                if (resourceSet == null)
                {
                    throw new BaseUmaException(ErrorCodes.InvalidResourceSetId, string.Format(ErrorDescriptions.TheResourceSetDoesntExist, resourceSetId));
                }
            }

            var resourceSetIds = policy.ResourceSetIds.ToList();

            resourceSetIds.AddRange(addResourceSetParameter.ResourceSets);
            policy.ResourceSetIds = resourceSetIds;
            var result = await _repositoryExceptionHelper.HandleException(
                ErrorDescriptions.ThePolicyCannotBeUpdated,
                () => _policyRepository.Update(policy));

            _umaServerEventSource.FinishAddResourceToAuthorizationPolicy(addResourceSetParameter.PolicyId, string.Join(",", addResourceSetParameter.ResourceSets));
            return(result);
        }
Пример #5
0
        public async Task <string> Execute(ShareResourceParameter shareResourceParameter)
        {
            if (shareResourceParameter == null)
            {
                throw new ArgumentNullException(nameof(shareResourceParameter));
            }

            if (string.IsNullOrWhiteSpace(shareResourceParameter.ResourceId))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheResourceIdMustBeSpecified);
            }

            if (shareResourceParameter.Scopes == null)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheScopesMustBeSpecified);
            }

            var resource = await _resourceSetRepository.Get(shareResourceParameter.ResourceId).ConfigureAwait(false);

            if (resource == null)
            {
                throw new UmaResourceNotFoundException();
            }

            if (!shareResourceParameter.Scopes.All(s => resource.Scopes.Contains(s)))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheScopeAreNotValid);
            }

            if (resource.Owner != shareResourceParameter.Owner)
            {
                throw new UmaNotAuthorizedException();
            }

            var sharedLink = new SharedLink
            {
                ConfirmationCode = Guid.NewGuid().ToString(),
                ResourceId       = resource.Id,
                Scopes           = shareResourceParameter.Scopes
            };

            if (!await _sharedLinkRepository.Insert(sharedLink))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InternalError, Errors.ErrorDescriptions.TheSharedLinkCannotBeInserted);
            }

            return(sharedLink.ConfirmationCode);
        }
Пример #6
0
        public async Task <bool> Execute(string id, string resourceId)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

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

            _umaServerEventSource.StartRemoveResourceFromAuthorizationPolicy(id, resourceId);
            var policy = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeRetrieved, id),
                () => _policyRepository.Get(id));

            if (policy == null)
            {
                return(false);
            }

            var resourceSet = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheResourceSetCannotBeRetrieved, resourceId),
                () => _resourceSetRepository.Get(resourceId));

            if (resourceSet == null)
            {
                throw new BaseUmaException(ErrorCodes.InvalidResourceSetId,
                                           string.Format(ErrorDescriptions.TheResourceSetDoesntExist, resourceId));
            }

            if (policy.ResourceSetIds == null || !policy.ResourceSetIds.Contains(resourceId))
            {
                throw new BaseUmaException(ErrorCodes.InvalidResourceSetId,
                                           ErrorDescriptions.ThePolicyDoesntContainResource);
            }

            var resourceSetIds = policy.ResourceSetIds.ToList();

            resourceSetIds.Remove(resourceId);
            policy.ResourceSetIds = resourceSetIds;
            var result = await _policyRepository.Update(policy).ConfigureAwait(false);

            _umaServerEventSource.FinishRemoveResourceFromAuthorizationPolicy(id, resourceId);
            return(result);
        }
Пример #7
0
        public async Task <ResourceValidationResult> IsAuthorized(string openidProvider, Ticket validTicket, ClaimTokenParameter claimTokenParameter)
        {
            if (string.IsNullOrWhiteSpace(openidProvider))
            {
                throw new ArgumentNullException(nameof(openidProvider));
            }

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

            if (validTicket.Lines == null || !validTicket.Lines.Any())
            {
                throw new ArgumentNullException(nameof(validTicket.Lines));
            }

            var resourceIds = validTicket.Lines.Select(l => l.ResourceSetId);
            var resources   = await _resourceSetRepository.Get(resourceIds);

            if (resources == null || !resources.Any() || resources.Count() != resourceIds.Count())
            {
                throw new BaseUmaException(ErrorCodes.InternalError, ErrorDescriptions.SomeResourcesDontExist);
            }

            ResourceValidationResult validationResult = null;

            foreach (var ticketLine in validTicket.Lines)
            {
                var ticketLineParameter = new TicketLineParameter(ticketLine.Scopes);
                if (validTicket.Audiences != null && validTicket.Audiences.Any())
                {
                    ticketLineParameter.ClientId = validTicket.Audiences.First();
                }

                var resource = resources.First(r => r.Id == ticketLine.ResourceSetId);
                validationResult = await Validate(openidProvider, ticketLineParameter, resource, claimTokenParameter).ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    _umaServerEventSource.AuthorizationPoliciesFailed(validTicket.Id);
                    return(validationResult);
                }
            }

            return(validationResult);
        }
Пример #8
0
        public async Task <AuthorizationPolicyResult> IsAuthorized(Ticket validTicket, string clientId, List <ClaimTokenParameter> claimTokenParameters)
        {
            if (validTicket == null)
            {
                throw new ArgumentNullException(nameof(validTicket));
            }

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

            var resourceSet = await _resourceSetRepository.Get(validTicket.ResourceSetId);

            if (resourceSet == null)
            {
                throw new BaseUmaException(ErrorCodes.InternalError,
                                           string.Format(ErrorDescriptions.TheResourceSetDoesntExist, validTicket.ResourceSetId));
            }

            if (resourceSet.Policies == null ||
                !resourceSet.Policies.Any())
            {
                return(new AuthorizationPolicyResult
                {
                    Type = AuthorizationPolicyResultEnum.Authorized
                });
            }

            foreach (var authorizationPolicy in resourceSet.Policies)
            {
                var result = await _basicAuthorizationPolicy.Execute(validTicket, authorizationPolicy, claimTokenParameters);

                if (result.Type != AuthorizationPolicyResultEnum.Authorized)
                {
                    _umaServerEventSource.AuthorizationPolicyFailed(authorizationPolicy.Id);
                    return(result);
                }
            }

            return(new AuthorizationPolicyResult
            {
                Type = AuthorizationPolicyResultEnum.Authorized
            });
        }
        private async Task CheckAddPermissionParameter(IEnumerable<AddPermissionParameter> addPermissionParameters)
        {
            // 1. Get resource sets.
            var resourceSets = await _repositoryExceptionHelper.HandleException(
                ErrorDescriptions.TheResourceSetsCannotBeRetrieved,
                () => _resourceSetRepository.Get(addPermissionParameters.Select(p => p.ResourceSetId)));

            // 2. Check parameters & scope exist.
            foreach (var addPermissionParameter in addPermissionParameters)
            {
                if (string.IsNullOrWhiteSpace(addPermissionParameter.ResourceSetId))
                {
                    throw new BaseUmaException(
                        ErrorCodes.InvalidRequestCode,
                        string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPermissionNames.ResourceSetId));
                }

                if (addPermissionParameter.Scopes == null ||
                    !addPermissionParameter.Scopes.Any())
                {
                    throw new BaseUmaException(
                        ErrorCodes.InvalidRequestCode,
                        string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPermissionNames.Scopes));
                }

                var resourceSet = resourceSets.FirstOrDefault(r => addPermissionParameter.ResourceSetId == r.Id);
                if (resourceSet == null)
                {
                    throw new BaseUmaException(
                        ErrorCodes.InvalidResourceSetId,
                        string.Format(ErrorDescriptions.TheResourceSetDoesntExist, addPermissionParameter.ResourceSetId));
                }

                if (resourceSet.Scopes == null ||
                    addPermissionParameter.Scopes.Any(s => !resourceSet.Scopes.Contains(s)))
                {
                    throw new BaseUmaException(
                        ErrorCodes.InvalidScope,
                        ErrorDescriptions.TheScopeAreNotValid);
                }
            }
        }
Пример #10
0
        public async Task <AuthorizationPolicyResult> IsAuthorized(Ticket validTicket, string clientId, ClaimTokenParameter claimTokenParameter)
        {
            if (validTicket == null)
            {
                throw new ArgumentNullException(nameof(validTicket));
            }

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

            if (validTicket.Lines == null || !validTicket.Lines.Any())
            {
                throw new ArgumentNullException(nameof(validTicket.Lines));
            }

            var resourceIds = validTicket.Lines.Select(l => l.ResourceSetId);
            var resources   = await _resourceSetRepository.Get(resourceIds);

            if (resources == null || !resources.Any() || resources.Count() != resourceIds.Count())
            {
                throw new BaseUmaException(ErrorCodes.InternalError, ErrorDescriptions.SomeResourcesDontExist);
            }

            AuthorizationPolicyResult validationResult = null;

            foreach (var ticketLine in validTicket.Lines)
            {
                var ticketLineParameter = new TicketLineParameter(clientId, ticketLine.Scopes, validTicket.IsAuthorizedByRo);
                var resource            = resources.First(r => r.Id == ticketLine.ResourceSetId);
                validationResult = await Validate(ticketLineParameter, resource, claimTokenParameter);

                if (validationResult.Type != AuthorizationPolicyResultEnum.Authorized)
                {
                    _umaServerEventSource.AuthorizationPoliciesFailed(validTicket.Id);
                    return(validationResult);
                }
            }

            return(validationResult);
        }
Пример #11
0
        public async Task <bool> Execute(UpdateResourceSetParameter udpateResourceSetParameter)
        {
            if (udpateResourceSetParameter == null)
            {
                throw new ArgumentNullException(nameof(udpateResourceSetParameter));
            }

            var json = JsonConvert.SerializeObject(udpateResourceSetParameter);

            _umaServerEventSource.StartToUpdateResourceSet(json);
            var resourceSet = new ResourceSet
            {
                Id      = udpateResourceSetParameter.Id,
                Name    = udpateResourceSetParameter.Name,
                Uri     = udpateResourceSetParameter.Uri,
                Type    = udpateResourceSetParameter.Type,
                Scopes  = udpateResourceSetParameter.Scopes,
                IconUri = udpateResourceSetParameter.IconUri,
                Owner   = udpateResourceSetParameter.Owner,
                AcceptPendingRequest = udpateResourceSetParameter.AcceptPendingRequest
            };

            if (string.IsNullOrWhiteSpace(udpateResourceSetParameter.Id))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, "id"));
            }
            _resourceSetParameterValidator.CheckResourceSetParameter(resourceSet);
            if (await _resourceSetRepository.Get(udpateResourceSetParameter.Id) == null)
            {
                return(false);
            }

            if (!await _resourceSetRepository.Update(resourceSet))
            {
                throw new BaseUmaException(ErrorCodes.InternalError, string.Format(ErrorDescriptions.TheResourceSetCannotBeUpdated, resourceSet.Id));
            }

            _umaServerEventSource.FinishToUpdateResourceSet(json);
            return(true);
        }
        public async Task <bool> Execute(ConfirmSharedLinkParameter confirmSharedLinkParameter)
        {
            if (confirmSharedLinkParameter == null)
            {
                throw new ArgumentNullException(nameof(confirmSharedLinkParameter));
            }

            if (string.IsNullOrWhiteSpace(confirmSharedLinkParameter.ConfirmationCode))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheConfirmationCodeMustBeSpecified);
            }

            var sharedLink = await _sharedLinkRepository.Get(confirmSharedLinkParameter.ConfirmationCode).ConfigureAwait(false);

            if (sharedLink == null)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheConfirmationCodeIsInvalid);
            }

            var resourceId = sharedLink.ResourceId;
            var resource   = await _resourceSetRepository.Get(resourceId).ConfigureAwait(false);

            if (resource == null)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InternalError, string.Format(Errors.ErrorDescriptions.TheResourceSetDoesntExist, resourceId));
            }

            if (resource.Owner == confirmSharedLinkParameter.Subject)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InternalError, Errors.ErrorDescriptions.TheSharedLinkCannotBeUsedByTheOwner);
            }

            var policy = new Policy
            {
                Id             = Guid.NewGuid().ToString(),
                ResourceSetIds = new List <string> {
                    resourceId
                },
                Claims = new List <Claim>
                {
                    new Claim
                    {
                        Type  = "sub",
                        Value = confirmSharedLinkParameter.Subject
                    }
                },
                Scopes = sharedLink.Scopes.ToList()
            };

            using (var transaction = new CommittableTransaction(new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                try
                {
                    await _sharedLinkRepository.Delete(sharedLink.ConfirmationCode).ConfigureAwait(false);

                    await _policyRepository.Add(policy).ConfigureAwait(false);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }

            return(true);
        }
        public async Task <AuthorizationPolicyResult> IsAuthorized(
            Ticket validTicket,
            Client client,
            ClaimTokenParameter claimTokenParameter,
            CancellationToken cancellationToken)
        {
            if (validTicket.Lines.Length == 0)
            {
                throw new ArgumentException(nameof(validTicket.Lines));
            }
            var handler = new JwtSecurityTokenHandler();
            var validationParameters = await client.CreateValidationParameters(_jwksStore, cancellationToken : cancellationToken).ConfigureAwait(false);

            var requester = handler.ValidateToken(claimTokenParameter.Token, validationParameters, out _);

            var resourceIds = validTicket.Lines.Select(l => l.ResourceSetId).ToArray();
            var resources   = await _resourceSetRepository.Get(cancellationToken, resourceIds).ConfigureAwait(false);

            if (resources.Length == 0 || resources.Length != resourceIds.Length)
            {
                return(new AuthorizationPolicyResult(AuthorizationPolicyResultKind.NotAuthorized, requester));
            }

            AuthorizationPolicyResult?validationResult = null;

            foreach (var ticketLine in validTicket.Lines)
            {
                var ticketLineParameter = new TicketLineParameter(
                    client.ClientId,
                    ticketLine.Scopes,
                    validTicket.IsAuthorizedByRo);
                var resource = resources.First(r => r.Id == ticketLine.ResourceSetId);
                validationResult = await Validate(
                    ticketLineParameter,
                    resource,
                    claimTokenParameter.Format,
                    requester,
                    cancellationToken)
                                   .ConfigureAwait(false);

                switch (validationResult.Result)
                {
                case AuthorizationPolicyResultKind.RequestSubmitted:
                    await _eventPublisher.Publish(
                        new AuthorizationRequestSubmitted(
                            Id.Create(),
                            validTicket.Id,
                            client.ClientId,
                            requester.Claims.Select(claim => new ClaimData {
                        Type = claim.Type, Value = claim.Value
                    }),
                            DateTimeOffset.UtcNow))
                    .ConfigureAwait(false);

                    return(validationResult);

                case AuthorizationPolicyResultKind.Authorized:
                    break;

                case AuthorizationPolicyResultKind.NotAuthorized:
                case AuthorizationPolicyResultKind.NeedInfo:
                default:
                {
                    await _eventPublisher.Publish(
                        new AuthorizationPolicyNotAuthorized(
                            Id.Create(),
                            validTicket.Id,
                            DateTimeOffset.UtcNow))
                    .ConfigureAwait(false);

                    return(validationResult);
                }
                }
            }

            return(validationResult !);
        }
Пример #14
0
        public async Task <bool> Execute(UpdateResourcePermissionsParameter updateResourcePermissionsParameter)
        {
            if (updateResourcePermissionsParameter == null)
            {
                throw new ArgumentNullException(nameof(updateResourcePermissionsParameter));
            }

            if (string.IsNullOrWhiteSpace(updateResourcePermissionsParameter.ResourceId))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheResourceIdMustBeSpecified);
            }

            var resource = await _resourceSetRepository.Get(updateResourcePermissionsParameter.ResourceId).ConfigureAwait(false);

            if (resource == null)
            {
                throw new UmaResourceNotFoundException();
            }

            if (updateResourcePermissionsParameter.Subject != resource.Owner)
            {
                throw new UmaNotAuthorizedException();
            }

            var policiesToBeUpdated = resource.AuthPolicies.ToList();
            var policiesToBeRemoved = new List <string>();
            var length = policiesToBeUpdated.Count();

            for (int i = length - 1; i >= 0; i--)
            {
                var policy          = policiesToBeUpdated.ElementAt(i);
                var policyParameter = updateResourcePermissionsParameter.PolicyIds.FirstOrDefault(p => p == policy.Id);
                if (policyParameter == null)
                {
                    policiesToBeUpdated.Remove(policy);
                    policiesToBeRemoved.Add(policy.Id);
                }
            }

            using (var transaction = new CommittableTransaction(new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                try
                {
                    var operations = new List <Task <bool> >();
                    foreach (var policyId in policiesToBeRemoved)
                    {
                        operations.Add(_policyRepository.Delete(policyId));
                    }

                    await Task.WhenAll(operations).ConfigureAwait(false);

                    transaction.Commit();
                    return(true);
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
Пример #15
0
        public async Task <bool> Execute(UpdatePolicyParameter updatePolicyParameter)
        {
            // Check the parameters
            if (updatePolicyParameter == null)
            {
                throw new ArgumentNullException(nameof(updatePolicyParameter));
            }

            if (string.IsNullOrWhiteSpace(updatePolicyParameter.PolicyId))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, "id"));
            }

            if (updatePolicyParameter.Rules == null || !updatePolicyParameter.Rules.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPolicyParameterNames.Rules));
            }

            _umaServerEventSource.StartUpdateAuthorizationPolicy(JsonConvert.SerializeObject(updatePolicyParameter));
            // Check the authorization policy exists.
            var policy = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeRetrieved, updatePolicyParameter.PolicyId),
                () => _policyRepository.Get(updatePolicyParameter.PolicyId));

            if (policy == null)
            {
                return(false);
            }

            policy.Rules = new List <PolicyRule>();
            // Check all the scopes are valid.
            foreach (var resourceSetId in policy.ResourceSetIds)
            {
                var resourceSet = await _resourceSetRepository.Get(resourceSetId);

                if (updatePolicyParameter.Rules.Any(r => r.Scopes != null && !r.Scopes.All(s => resourceSet.Scopes.Contains(s))))
                {
                    throw new BaseUmaException(ErrorCodes.InvalidScope, ErrorDescriptions.OneOrMoreScopesDontBelongToAResourceSet);
                }
            }

            // Update the authorization policy.
            foreach (var ruleParameter in updatePolicyParameter.Rules)
            {
                var claims = new List <Claim>();
                if (ruleParameter.Claims != null)
                {
                    claims = ruleParameter.Claims.Select(c => new Claim
                    {
                        Type  = c.Type,
                        Value = c.Value
                    }).ToList();
                }

                policy.Rules.Add(new PolicyRule
                {
                    Id = ruleParameter.Id,
                    ClientIdsAllowed             = ruleParameter.ClientIdsAllowed,
                    IsResourceOwnerConsentNeeded = ruleParameter.IsResourceOwnerConsentNeeded,
                    Scopes         = ruleParameter.Scopes,
                    Script         = ruleParameter.Script,
                    Claims         = claims,
                    OpenIdProvider = ruleParameter.OpenIdProvider
                });
            }

            var result = await _repositoryExceptionHelper.HandleException(
                string.Format(ErrorDescriptions.TheAuthorizationPolicyCannotBeUpdated, updatePolicyParameter.PolicyId),
                () => _policyRepository.Update(policy));

            _umaServerEventSource.FinishUpdateAuhthorizationPolicy(JsonConvert.SerializeObject(updatePolicyParameter));
            return(result);
        }