private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();

            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));

            var allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && NeedsPolicyValidation(directive))
            {
                allowed = await AuthorizeWithPolicyAsync(
                    context, directive, principal)
                          .ConfigureAwait(false);
            }
#endif
            if (allowed)
            {
                await next(context);
            }
            else if (context.Result == null)
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }
예제 #2
0
        private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
#if !ASPNETCLASSIC
            IAuthorizationService authorizeService = context
                                                     .Service <IAuthorizationService>();
#endif
            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();
            bool allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && !string.IsNullOrEmpty(directive.Policy))
            {
                AuthorizationResult result = await authorizeService
                                             .AuthorizeAsync(principal, directive.Policy);

                allowed = result.Succeeded;
            }
#endif

            if (allowed)
            {
                await next(context);
            }
            else
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }