Example #1
0
 /// <summary>
 /// Initialize a new <see cref="AuthorizeFilter"/> instance.
 /// </summary>
 /// <param name="policy">Authorization policy to be used.</param>
 public AuthorizeFilter(AuthorizationPolicy policy)
 {
     if (policy == null)
     {
         throw new ArgumentNullException(nameof(policy));
     }
     Policy = policy;
 }
        /// <summary>
        /// Combines the specified <paramref name="policy"/> into the current instance.
        /// </summary>
        /// <param name="policy">The <see cref="AuthorizationPolicy"/> to combine.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public AuthorizationPolicyBuilder Combine(AuthorizationPolicy policy)
        {
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            AddAuthenticationSchemes(policy.AuthenticationSchemes.ToArray());
            AddRequirements(policy.Requirements.ToArray());
            return this;
        }
Example #3
0
        /// <summary>
        /// Add an authorization policy with the provided name.
        /// </summary>
        /// <param name="name">The name of the policy.</param>
        /// <param name="policy">The authorization policy.</param>
        public void AddPolicy(string name, AuthorizationPolicy policy)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

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

            PolicyMap[name] = policy;
        }
Example #4
0
        /// <summary>
        /// Checks if a user meets a specific authorization policy
        /// </summary>
        /// <param name="service">The authorization service.</param>
        /// <param name="user">The user to check the policy against.</param>
        /// <param name="policy">The policy to check against a specific context.</param>
        /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
        public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, AuthorizationPolicy policy)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

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

            return service.AuthorizeAsync(user, resource: null, policy: policy);
        }
Example #5
0
        /// <summary>
        /// Checks if a user meets a specific authorization policy
        /// </summary>
        /// <param name="service">The authorization service.</param>
        /// <param name="user">The user to check the policy against.</param>
        /// <param name="resource">The resource the policy should be checked with.</param>
        /// <param name="policy">The policy to check against a specific context.</param>
        /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
        public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, AuthorizationPolicy policy)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

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

            return service.AuthorizeAsync(user, resource, policy.Requirements.ToArray());
        }
 public static async Task CheckAsync(this IAuthorizationService authorizationService, object resource, AuthorizationPolicy policy)
 {
     if (!await authorizationService.IsGrantedAsync(resource, policy))
     {
         throw new AbpAuthorizationException("Authorization failed! Given policy has not granted for given resource: " + resource);
     }
 }
 /// <summary>
 /// Creates a new instance of <see cref="AuthorizationPolicyBuilder"/>.
 /// </summary>
 /// <param name="policy">The <see cref="AuthorizationPolicy"/> to build.</param>
 public AuthorizationPolicyBuilder(AuthorizationPolicy policy)
 {
     Combine(policy);
 }
 public static async Task <bool> IsGrantedAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     return((await authorizationService.AuthorizeAsync(policy).ConfigureAwait(false)).Succeeded);
 }
 public static async Task <AuthorizationResult> AuthorizeAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     return(await AuthorizeAsync(
                authorizationService,
                null,
                policy
                ).ConfigureAwait(false));
 }
 public static async Task <AuthorizationResult> AuthorizeAsync(this IAuthorizationService authorizationService, object resource, AuthorizationPolicy policy)
 {
     return(await authorizationService.AuthorizeAsync(
                authorizationService.AsAbpAuthorizationService().CurrentPrincipal,
                resource,
                policy
                ).ConfigureAwait(false));
 }
 public static async Task CheckAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     if (!await authorizationService.IsGrantedAsync(policy).ConfigureAwait(false))
     {
         throw new AbpAuthorizationException("Authorization failed! Given policy has not granted.");
     }
 }
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                // EndpointRoutingMiddleware uses this flag to check if the Authorization middleware processed auth metadata on the endpoint.
                // The Authorization middleware can only make this claim if it observes an actual endpoint.
                context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
            }

            // IMPORTANT: Changes to authorization logic should be mirrored in MVC's AuthorizeFilter
            var authorizeData = endpoint?.Metadata.GetOrderedMetadata <IAuthorizeData>() ?? Array.Empty <IAuthorizeData>();
            var policy        = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);

            if (policy == null)
            {
                await _next(context);

                return;
            }

            // Policy evaluator has transient lifetime so it fetched from request services instead of injecting in constructor
            var policyEvaluator = context.RequestServices.GetRequiredService <IPolicyEvaluator>();

            var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);

            // Allow Anonymous skips all authorization
            if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null)
            {
                await _next(context);

                return;
            }

            // Note that the resource will be null if there is no matched endpoint
            var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource : endpoint);

            if (authorizeResult.Challenged)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ChallengeAsync(scheme);
                    }
                }
                else
                {
                    await context.ChallengeAsync();
                }

                return;
            }
            else if (authorizeResult.Forbidden)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ForbidAsync(scheme);
                    }
                }
                else
                {
                    await context.ForbidAsync();
                }

                return;
            }

            await _next(context);
        }
        /// <summary>
        /// Checks if a user meets a specific authorization policy against the specified resource.
        /// </summary>
        /// <param name="service">The <see cref="IAuthorizationService"/> providing authorization.</param>
        /// <param name="user">The user to evaluate the policy against.</param>
        /// <param name="policy">The policy to evaluate.</param>
        /// <returns>
        /// A flag indicating whether policy evaluation has succeeded or failed.
        /// This value is <value>true</value> when the user fulfills the policy, otherwise <value>false</value>.
        /// </returns>
        public static Task <AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, AuthorizationPolicy policy)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

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

            return(service.AuthorizeAsync(user, resource: null, policy: policy));
        }
 public static async Task CheckAsync(this IAuthorizationService authorizationService, object resource, AuthorizationPolicy policy)
 {
     if (!await authorizationService.IsGrantedAsync(resource, policy))
     {
         throw new AbpAuthorizationException(code: AbpAuthorizationErrorCodes.GivenPolicyHasNotGrantedForGivenResource)
               .WithData("ResourceName", resource);
     }
 }
 public static async Task <bool> IsGrantedAsync(this IAuthorizationService authorizationService, object resource, AuthorizationPolicy policy)
 {
     return((await authorizationService.AuthorizeAsync(resource, policy)).Succeeded);
 }
Example #16
0
        private Task <AuthorizationPolicy> GetCachedPolicy(ref Task <AuthorizationPolicy> cachedPolicy, AuthorizationPolicy currentPolicy)
        {
            var local = cachedPolicy;

            if (local == null || local.Result != currentPolicy)
            {
                cachedPolicy = local = Task.FromResult(currentPolicy);
            }
            return(local);
        }
Example #17
0
 /// <summary>
 /// Creates a new instance of <see cref="AuthorizationPolicyBuilder"/>.
 /// </summary>
 /// <param name="policy">The <see cref="AuthorizationPolicy"/> to copy.</param>
 public AuthorizationPolicyBuilder(AuthorizationPolicy policy)
 {
     Combine(policy);
 }
        /// <summary>
        /// Checks if a user meets a specific authorization policy
        /// </summary>
        /// <param name="service">The authorization service.</param>
        /// <param name="user">The user to check the policy against.</param>
        /// <param name="resource">The resource the policy should be checked with.</param>
        /// <param name="policy">The policy to check against a specific context.</param>
        /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
        public static Task <bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, AuthorizationPolicy policy)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

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

            return(service.AuthorizeAsync(user, resource, policy.Requirements.ToArray()));
        }
        /// <summary>
        /// Invokes the middleware performing authorization.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                // EndpointRoutingMiddleware uses this flag to check if the Authorization middleware processed auth metadata on the endpoint.
                // The Authorization middleware can only make this claim if it observes an actual endpoint.
                context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
            }

            // IMPORTANT: Changes to authorization logic should be mirrored in MVC's AuthorizeFilter
            var authorizeData = endpoint?.Metadata.GetOrderedMetadata <IAuthorizeData>() ?? Array.Empty <IAuthorizeData>();
            var policy        = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);

            if (policy == null)
            {
                await _next(context);

                return;
            }

            // Policy evaluator has transient lifetime so it's fetched from request services instead of injecting in constructor
            var policyEvaluator = context.RequestServices.GetRequiredService <IPolicyEvaluator>();

            var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);

            if (authenticateResult?.Succeeded ?? false)
            {
                if (context.Features.Get <IAuthenticateResultFeature>() is IAuthenticateResultFeature authenticateResultFeature)
                {
                    authenticateResultFeature.AuthenticateResult = authenticateResult;
                }
                else
                {
                    var authFeatures = new AuthenticationFeatures(authenticateResult);
                    context.Features.Set <IHttpAuthenticationFeature>(authFeatures);
                    context.Features.Set <IAuthenticateResultFeature>(authFeatures);
                }
            }

            // Allow Anonymous still wants to run authorization to populate the User but skips any failure/challenge handling
            if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null)
            {
                await _next(context);

                return;
            }

            object?resource;

            if (AppContext.TryGetSwitch(SuppressUseHttpContextAsAuthorizationResource, out var useEndpointAsResource) && useEndpointAsResource)
            {
                resource = endpoint;
            }
            else
            {
                resource = context;
            }

            var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult !, context, resource);

            var authorizationMiddlewareResultHandler = context.RequestServices.GetRequiredService <IAuthorizationMiddlewareResultHandler>();
            await authorizationMiddlewareResultHandler.HandleAsync(_next, context, policy, authorizeResult);
        }
 public static async Task CheckAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     if (!await authorizationService.IsGrantedAsync(policy))
     {
         throw new AbpAuthorizationException(code: AbpAuthorizationErrorCodes.GivenPolicyHasNotGranted);
     }
 }
 public static Task <AuthorizationResult> AuthorizeAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     return(AuthorizeAsync(authorizationService, authorizationService.AsAbpAuthorizationService().CurrentPrincipal,
                           policy
                           ));
 }
Example #22
0
        private async Task EvaluatePolicy(HttpContext context, Endpoint endpoint, IEnumerable <IAuthorizeData> authorizeData)
        {
            // IMPORTANT: Changes to authorization logic should be mirrored in MVC's AuthorizeFilter
            var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);

            if (policy == null)
            {
                await _next(context);

                return;
            }

            // Policy evaluator has transient lifetime so it fetched from request services instead of injecting in constructor
            var policyEvaluator = context.RequestServices.GetRequiredService <IPolicyEvaluator>();

            var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);

            // Allow Anonymous skips all authorization
            if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null)
            {
                await _next(context);

                return;
            }

            // Note that the resource will be null if there is no matched endpoint
            var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource : endpoint);

            if (authorizeResult.Challenged)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ChallengeAsync(scheme);
                    }
                }
                else
                {
                    await context.ChallengeAsync();
                }

                return;
            }
            else if (authorizeResult.Forbidden)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ForbidAsync(scheme);
                    }
                }
                else
                {
                    await context.ForbidAsync();
                }

                return;
            }

            await _next(context);
        }