public void VerifyAuthorization(ClaimsPrincipal user, IAuthorizationRequirement requirement, object resource = null)
 {
     if (!IsAuthorized(user, requirement, resource))
     {
         throw new SecurityException();
     }
 }
        public void OnProvidersExecuting_DefaultPolicyProvider_NoAuthorizationData_NoFilterCreated()
        {
            // Arrange
            var requirements = new IAuthorizationRequirement[]
            {
                new AssertionRequirement((con) => { return(true); })
            };
            var authorizationPolicy = new AuthorizationPolicy(requirements, new string[] { "dingos" });
            var authOptions         = Options.Create(new AuthorizationOptions());

            authOptions.Value.AddPolicy("Base", authorizationPolicy);
            var policyProvider = new DefaultAuthorizationPolicyProvider(authOptions);

            var provider        = new AuthorizationApplicationModelProvider(policyProvider);
            var defaultProvider = new DefaultApplicationModelProvider(Options.Create(new MvcOptions()));

            // Act
            var action = GetBaseControllerActionModel(provider, defaultProvider);

            // Assert
            var authorizationFilter = Assert.IsType <AuthorizeFilter>(Assert.Single(action.Filters));

            Assert.NotNull(authorizationFilter.Policy);
            Assert.Null(authorizationFilter.AuthorizeData);
            Assert.Null(authorizationFilter.PolicyProvider);
        }
        public bool IsAuthorized(ClaimsPrincipal user, IAuthorizationRequirement requirement, object resource = null)
        {
            Contract.Requires <ArgumentNullException>(user != null, nameof(user));
            Contract.Requires <ArgumentNullException>(requirement != null, nameof(requirement));

            return(authorizationService.AuthorizeAsync(user, resource, requirement).GetAwaiter().GetResult().Succeeded);
        }
        private AuthorizationHandlerContext CreateAuthorizationHandlerContext(Type controllerType, string action)
        {
            var actionContext = new ActionContext();

            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext.Setup(c => c.Request)
            .Returns(Mock.Of <HttpRequest>());

            actionContext.HttpContext = mockHttpContext.Object;
            actionContext.RouteData   = new RouteData();

            var actionDescriptor = new ControllerActionDescriptor
            {
                ControllerTypeInfo = controllerType.GetTypeInfo(),
                MethodInfo         = controllerType.GetMethod(action)
            };

            actionContext.ActionDescriptor = actionDescriptor;

            var resource = new Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext(actionContext, new List <IFilterMetadata>());

            var requirements = new IAuthorizationRequirement[] { new ConventionBasedRequirement() };

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, _userId),
            };
            var user    = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
            var context = new AuthorizationHandlerContext(requirements, user, resource);

            return(context);
        }
Esempio n. 5
0
        public async Task <IActionResult> OnPostAsync(int?id, ContactStatus status)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Contact = await Context.Contact.FindAsync(id);

            if (Contact == null)
            {
                return(NotFound());
            }
            IAuthorizationRequirement operation = status == ContactStatus.Approved ? ContactOperations.Approve : ContactOperations.Reject;
            var isAuthorized = await AuthorizationService.AuthorizeAsync(User, Contact, operation);

            if (!isAuthorized.Succeeded)
            {
                return(new ChallengeResult());
            }
            Contact.status = status;
            Context.Update(Contact);
            await Context.SaveChangesAsync();

            return(Page());
            //return RedirectToPage("./Index");
        }
 public static AuthorizationPolicyBuilder RequireCustomClaim(
     this AuthorizationPolicyBuilder builder,
     IAuthorizationRequirement customRequirement)
 {
     builder.AddRequirements(customRequirement);
     return(builder);
 }
        private Task <AuthorizationResult> ExecuteAuthorizationHandler(IAuthorizationRequirement requirement, CancellationToken cancellationToken)
        {
            var requirementType = requirement.GetType();
            var handlerType     = FindHandlerType(requirement);

            if (handlerType == null)
            {
                throw new InvalidOperationException($"Could not find an authorization handler type for requirement type \"{requirementType.Name}\"");
            }

            var handlers = _serviceProvider.GetService(typeof(IEnumerable <>).MakeGenericType(handlerType)) as IEnumerable <object>;

            if (handlers == null || handlers.Count() == 0)
            {
                throw new InvalidOperationException($"Could not find an authorization handler implementation for requirement type \"{requirementType.Name}\"");
            }

            if (handlers.Count() > 1)
            {
                throw new InvalidOperationException($"Multiple authorization handler implementations were found for requirement type \"{requirementType.Name}\"");
            }

            var serviceHandler     = handlers.First();
            var serviceHandlerType = serviceHandler.GetType();

            var methodInfo = _handlerMethodInfo.GetOrAdd(serviceHandlerType,
                                                         handlerMethodKey =>
            {
                return(serviceHandlerType.GetMethods()
                       .Where(x => x.Name == nameof(IAuthorizationHandler <IAuthorizationRequirement> .Handle))
                       .FirstOrDefault());
            });

            return((Task <AuthorizationResult>)methodInfo.Invoke(serviceHandler, new object[] { requirement, cancellationToken }));
        }
Esempio n. 8
0
        // And this is where the magic happens.
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            // Check to see if there's a configured policy with the name.
            var _policy = _options.GetPolicy(policyName);

            if (_policy == null)
            {
                // There's no matching policy name in the policies configured in start
                // So let's do our thing.

                // For our sample we have the following policy name format,
                // ClaimName|ExpectedValue and we assume that neither the claim name nor the
                // value have a | character in them, because it's only a sample

                var policyDetails = policyName.Split('|');

                if (policyDetails.Length != 2)
                {
                    return(Task.FromResult((AuthorizationPolicy)null));
                }

                // Now we can create our custom requirements with the right parameters
                // then build a policy around them, and finally return that policy for evaluation.

                var requirements = new IAuthorizationRequirement[1];
                requirements[0] = new CustomAuthorizationRequirement {
                    ClaimType = policyDetails[0], ClaimValue = policyDetails[1]
                };

                return(Task.FromResult(new AuthorizationPolicyBuilder().AddRequirements(requirements).Build()));
            }

            return(Task.FromResult(_policy));
        }
        public async Task should_fail_for_role_without_policy_in_it()
        {
            // given
            string authorizedRoleName = "basic.user";
            string policyInRole       = "AddPage";
            IAuthorizationRequirement basicUserRequirement = AddMockRoleAndCreateRequirement(authorizedRoleName, policyInRole);

            string adminRoleName     = "admin.rooty";
            string policyInAdminRole = "DeletePage";
            IAuthorizationRequirement adminUserRequirement = AddMockRoleAndCreateRequirement(adminRoleName, policyInAdminRole);

            var requirements = new List <IAuthorizationRequirement>();

            requirements.Add(basicUserRequirement);
            requirements.Add(adminUserRequirement);

            ClaimsPrincipal user = CreateClaimsPrincipal(authorizedRoleName);

            var context = new AuthorizationHandlerContext(requirements, user, null);

            // when
            await _rolesAuthorizationHandler.HandleAsync(context);

            // then
            context.HasSucceeded.ShouldBeFalse();
        }
 public PermissionCheckContext(ActionDescriptor actionDescriptor, HttpContext httpContext, ICurrentUserContext currentUserContext, IAuthorizationRequirement requirement)
 {
     ActionDescriptor   = actionDescriptor;
     HttpContext        = httpContext;
     CurrentUserContext = currentUserContext;
     Requirement        = requirement;
 }
        public void OnProvidersExecuting_NonDefaultPolicyProvider_HasNoPolicy_HasPolicyProviderAndAuthorizeData()
        {
            // Arrange
            var requirements = new IAuthorizationRequirement[]
            {
                new AssertionRequirement((con) => { return(true); })
            };
            var authorizationPolicy             = new AuthorizationPolicy(requirements, new string[] { "dingos" });
            var authorizationPolicyProviderMock = new Mock <IAuthorizationPolicyProvider>();

            authorizationPolicyProviderMock
            .Setup(s => s.GetPolicyAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(authorizationPolicy))
            .Verifiable();

            var provider        = new AuthorizationApplicationModelProvider(authorizationPolicyProviderMock.Object);
            var defaultProvider = new DefaultApplicationModelProvider(Options.Create(new MvcOptions()));

            // Act
            var action = GetBaseControllerActionModel(provider, defaultProvider);

            // Assert
            var actionFilter = Assert.IsType <AuthorizeFilter>(Assert.Single(action.Filters));

            Assert.Null(actionFilter.Policy);
            Assert.NotNull(actionFilter.AuthorizeData);
            Assert.NotNull(actionFilter.PolicyProvider);
        }
Esempio n. 12
0
        public void CuandoUserTieneClaimsPeroConClaimResourceAccessVacioResultadoEsSuccess()
        {
            //
            var role           = "admin";
            var audience       = "TestBackend";
            var hasRole        = new HasRoleHandler(audience);
            var resourceAccess = new { TestBackend = new { roles = new string[] { role } } };

            var identity = new ClaimsIdentity();

            identity.AddClaim(new Claim(ClaimTypes.Name, "Michael Emir"));
            identity.AddClaim(new Claim(ClaimTypes.Country, "El Salvador"));
            identity.AddClaim(new Claim("resource_access", JsonConvert.SerializeObject(resourceAccess)));

            var userClaims      = new ClaimsPrincipal(identity); //Usuario
            var roleRequirement = new HasRoleRequirement(role);
            var requirements    = new IAuthorizationRequirement[] { roleRequirement };
            var context         = new AuthorizationHandlerContext(requirements, userClaims, null);

            //Act
            hasRole.ValidateRoleRequirement(context, roleRequirement);

            //Assert
            Assert.IsTrue(context.HasSucceeded);
            Assert.IsFalse(context.HasFailed);
        }
        public AuthorizationPolicy(string name, IAuthorizationRequirement requirement)
        {
            Requirements          = new List <IAuthorizationRequirement>();
            AuthenticationSchemes = new List <string>();

            this.Name = name;
            this.Requirements.Add(requirement);
        }
Esempio n. 14
0
 protected void UseRequirement(IAuthorizationRequirement requirement)
 {
     if (requirement == null)
     {
         return;
     }
     _requirements.Add(requirement);
 }
 /// <summary>
 /// Creates a new <see cref="AuthorizationPipeline{TRequest, TResponse}"/>
 /// which uses a <paramref name="requirement"/> to determine whether or
 /// not the current user can access the <typeparamref name="TResponse"/>.
 /// </summary>
 /// <param name="authorizationService">The service used check the current user's permissions.</param>
 /// <param name="httpContextAccessor">The http context used to get the current user.</param>
 /// <param name="requirement">The requirement to authorize against.</param>
 public AuthorizationPipeline(
     IAuthorizationService authorizationService,
     IHttpContextAccessor httpContextAccessor,
     IAuthorizationRequirement requirement) :
     this(authorizationService, httpContextAccessor)
 {
     this.requirements = new IAuthorizationRequirement[] { requirement };
 }
        private static void AppendFailureLine(
            StringBuilder stringBuilder,
            IAuthorizationRequirement authorizationRequirement)
        {
            switch (authorizationRequirement)
            {
            case ClaimsAuthorizationRequirement claimsAuthorizationRequirement:
                stringBuilder.Append("Required claim '");
                stringBuilder.Append(claimsAuthorizationRequirement.ClaimType);
                if (claimsAuthorizationRequirement.AllowedValues == null || !claimsAuthorizationRequirement.AllowedValues.Any())
                {
                    stringBuilder.AppendLine("' is not present.");
                }
                else
                {
                    stringBuilder.Append("' with any value of '");
                    stringBuilder.Append(string.Join(", ", claimsAuthorizationRequirement.AllowedValues));
                    stringBuilder.AppendLine("' is not present.");
                }
                break;

            case DenyAnonymousAuthorizationRequirement denyAnonymousAuthorizationRequirement:
                stringBuilder.AppendLine("The current user must be authenticated.");
                break;

            case NameAuthorizationRequirement nameAuthorizationRequirement:
                stringBuilder.Append("The current user name must match the name '");
                stringBuilder.Append(nameAuthorizationRequirement.RequiredName);
                stringBuilder.AppendLine("'.");
                break;

            case OperationAuthorizationRequirement operationAuthorizationRequirement:
                stringBuilder.Append("Required operation '");
                stringBuilder.Append(operationAuthorizationRequirement.Name);
                stringBuilder.AppendLine("' was not present.");
                break;

            case RolesAuthorizationRequirement rolesAuthorizationRequirement:
                if (rolesAuthorizationRequirement.AllowedRoles == null || !rolesAuthorizationRequirement.AllowedRoles.Any())
                {
                    // This should never happen.
                    stringBuilder.AppendLine("Required roles are not present.");
                }
                else
                {
                    stringBuilder.Append("Required roles '");
                    stringBuilder.Append(string.Join(", ", rolesAuthorizationRequirement.AllowedRoles));
                    stringBuilder.AppendLine("' are not present.");
                }
                break;

            default:
                stringBuilder.Append("Requirement '");
                stringBuilder.Append(authorizationRequirement.GetType().Name);
                stringBuilder.AppendLine("' was not satisfied.");
                break;
            }
        }
Esempio n. 17
0
        private async Task <bool> IsUserAuthorizedAsync(Product product, IAuthorizationRequirement operation)
        {
            AuthorizationResult isAuthorized = await _authorizationService.AuthorizeAsync(
                User,
                product,
                operation
                );

            return(isAuthorized.Succeeded);
        }
Esempio n. 18
0
        private AuthorizationHandlerContext CreateAuthorizationHandlerContext(List <Claim> claims)
        {
            var requirements = new IAuthorizationRequirement[] { new CustomBasedRequirement() };

            claims.Add(new Claim(ClaimTypes.Name, _userId));
            var user    = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
            var context = new AuthorizationHandlerContext(requirements, user, null);

            return(context);
        }
        private void AccessDenied(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        {
            var httpContext = _accessor.HttpContext;

            httpContext.Items.TryAdd(
                AuthLockedResponse.AuthLockedKey,
                new AuthLockedResponse(httpContext.Request.Path)
                );
            context.Succeed(requirement);
        }
Esempio n. 20
0
        /// <summary>
        /// Called to mark the specified <paramref name="requirement"/> as being
        /// successfully evaluated.
        /// </summary>
        /// <param name="requirement">The requirement whose evaluation has succeeded.</param>
        /// <param name="message">Optional: message we want to pass.</param>
        public virtual void Succeed(IAuthorizationRequirement requirement, string message = null)
        {
            if (!string.IsNullOrWhiteSpace(message))
            {
                Messages.Add(requirement, message);
            }

            _pendingRequirements.Remove(requirement);
            _succeededRequirements.Add(requirement);
        }
Esempio n. 21
0
        private FilterDescriptor GetFilterDescriptor(IAuthorizationRequirement requirement, int filterScope)
        {
            var requirements = new List <IAuthorizationRequirement>()
            {
                requirement
            };
            var policy = new AuthorizationPolicy(requirements, new List <string>());

            return(new FilterDescriptor(new AuthorizeFilter(policy), 30));
        }
Esempio n. 22
0
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            GetPolicyCount++;

            var requirements = new IAuthorizationRequirement[]
            {
                new AssertionRequirement((con) => { return(true); })
            };

            return(Task.FromResult(new AuthorizationPolicy(requirements, new string[] { })));
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, TEntity resource)
        {
            IAuthorizationRequirement delegateRequirement = CreateInstance <TDelegateRequirement>();
            var delegateContext = new AuthorizationHandlerContext(new[] { delegateRequirement }, context.User, _delegateResourceFn.Invoke(resource));
            await _delegateHandler.HandleAsync(delegateContext);

            if (delegateContext.HasSucceeded)
            {
                context.Succeed(requirement);
            }
        }
        public void PropertiesShouldBeSet()
        {
            var requirements = new IAuthorizationRequirement[0];
            var user         = new ClaimsPrincipal();

            var context = new AuthorizationContext(requirements, user, requirements);

            Assert.AreSame(requirements, context.Requirements);
            Assert.AreSame(user, context.User);
            Assert.AreSame(requirements, context.Resource);
        }
        public static async Task AssertAuthorizedAsync(
            this IUserAuthorizationService userAuthorizationService,
            object resource,
            IAuthorizationRequirement requirement)
        {
            var result = await userAuthorizationService.AuthorizeAsync(resource, requirement);

            if (!result.Succeeded)
            {
                throw new UserUnauthorizedException();
            }
        }
        protected async Task <bool> IsAuthorizedAsync(RegionEntity region, IAuthorizationRequirement requirement)
        {
            var identity = new ClaimsIdentity();

            identity.AddClaim(new Claim("sub", Guid.NewGuid().ToString()));
            identity.AddClaim(new Claim("email", Email));
            _regionMembershipRoleClaimValues.ForEach(rm => identity.AddRegionMembershipRole(rm));

            var principal = new ClaimsPrincipal(identity);

            return((await _authorizationService.AuthorizeAsync(principal, region, requirement)).Succeeded);
        }
        public void SucceedShouldUpdatePendingRequirements()
        {
            var requirements = new IAuthorizationRequirement[]
            {
                new DenyAnonymousAuthorizationRequirement()
            };

            var context = new AuthorizationContext(requirements, null, null);

            Assert.AreEqual(requirements.Length, context.PendingRequirements.Count());
            context.Succeed(requirements[0]);
            Assert.IsFalse(context.PendingRequirements.Any(), "context.PendingRequirements.Any()");
        }
Esempio n. 28
0
 public static void Add(string key, IAuthorizationRequirement requirement)
 {
     if (Requirments.ContainsKey(key))
     {
         Requirments[key].Add(requirement);
     }
     else
     {
         Requirments.Add(key, new List <IAuthorizationRequirement> {
             requirement
         });
     }
 }
Esempio n. 29
0
        /// <summary>
        /// Checks if a user meets a specific requirement for the specified resource
        /// </summary>
        /// <param name="service">The <see cref="IAuthorizationService"/>.</param>
        /// <param name="user"></param>
        /// <param name="resource"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, IAuthorizationRequirement requirement)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

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

            return service.AuthorizeAsync(user, resource, new IAuthorizationRequirement[] { requirement });
        }
 private static PolicyDefinition CreatePolicyDefinition(string policyName, IAuthorizationRequirement authorizationRequirement = null)
 {
     return(new PolicyDefinition {
         PolicyName = policyName,
         ConfigurationAction = policyBuilder =>
         {
             policyBuilder.RequireDefaultPolicy();
             if (authorizationRequirement != null)
             {
                 policyBuilder.Requirements.Add(authorizationRequirement);
             }
         },
     });
 }
    public async Task CheckAsync(object resource, IAuthorizationRequirement requirement)
    {
        var claimIdentity = new ClaimsIdentity(new List <Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, _currentUser.Id.ToString())
        });

        var result = await _authorizationService
                     .AuthorizeAsync(new ClaimsPrincipal(claimIdentity), resource, requirement);

        if (!result.Succeeded)
        {
            throw new ResourceAuthorizationException(resource.GetType().Name);
        }
    }
        public static void AddTeamOwnerPolicy(this AuthorizationOptions options, IServiceProvider provider)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // build team ownership policy
            var ownershipRequirements = new IAuthorizationRequirement[]
            {
                    new DenyAnonymousAuthorizationRequirement(),
                    (TeamOwnerRequirement)provider.GetService(typeof(TeamOwnerRequirement))
            };

            var ownershipPolicy = new AuthorizationPolicy(ownershipRequirements, new string[0]);

            options.AddPolicy(AuthorizationDefaults.PolicyTeamOwner, ownershipPolicy);
        }
Esempio n. 33
0
 public void Succeed(IAuthorizationRequirement requirement)
 {
     _succeedCalled = true;
     _pendingRequirements.Remove(requirement);
 }