Exemple #1
0
    public async Task InvokeAsync(IDirectiveContext context)
    {
        AuthorizeDirective directive = context.Directive
                                       .ToObject <AuthorizeDirective>();

        if (directive.Apply == ApplyPolicy.AfterResolver)
        {
            await _next(context).ConfigureAwait(false);

            AuthorizeResult state =
                await _authorizationHandler.AuthorizeAsync(context, directive)
                .ConfigureAwait(false);

            if (state != AuthorizeResult.Allowed && !IsErrorResult(context))
            {
                SetError(context, directive, state);
            }
        }
        else
        {
            AuthorizeResult state =
                await _authorizationHandler.AuthorizeAsync(context, directive)
                .ConfigureAwait(false);

            if (state == AuthorizeResult.Allowed)
            {
                await _next(context).ConfigureAwait(false);
            }
            else
            {
                SetError(context, directive, state);
            }
        }
    }
Exemple #2
0
    private static async Task <AuthorizeResult> AuthorizeWithPolicyAsync(
        IMiddlewareContext context,
        AuthorizeDirective directive,
        ClaimsPrincipal principal)
    {
        IServiceProvider      services         = context.Service <IServiceProvider>();
        IAuthorizationService?authorizeService =
            services.GetService <IAuthorizationService>();
        IAuthorizationPolicyProvider?policyProvider =
            services.GetService <IAuthorizationPolicyProvider>();

        if (authorizeService == null || policyProvider == null)
        {
            // authorization service is not configured so the user is
            // authorized with the previous checks.
            return(string.IsNullOrWhiteSpace(directive.Policy)
                ? AuthorizeResult.Allowed
                : AuthorizeResult.NotAllowed);
        }

        AuthorizationPolicy?policy = null;

        if ((directive.Roles is null || directive.Roles.Count == 0) &&
            string.IsNullOrWhiteSpace(directive.Policy))
        {
            policy = await policyProvider.GetDefaultPolicyAsync()
                     .ConfigureAwait(false);

            if (policy == null)
            {
                return(AuthorizeResult.NoDefaultPolicy);
            }
        }
Exemple #3
0
    public void CreateInstance_Policy_PolicyIsSet()
    {
        // arrange
        // act
        var authorizeDirective = new AuthorizeDirective("abc");

        // assert
        Assert.Equal("abc", authorizeDirective.Policy);
        Assert.Null(authorizeDirective.Roles);
    }
Exemple #4
0
    public void CreateInstance_PolicyRoles_PolicyIsSetRolesIsNull()
    {
        // arrange
        // act
        var authorizeDirective = new AuthorizeDirective(
            "abc", Array.Empty <string>());

        // assert
        Assert.Equal("abc", authorizeDirective.Policy);
        Assert.Empty(authorizeDirective.Roles);
    }
Exemple #5
0
    public void CreateInstance_Roles_RolesHasItems()
    {
        // arrange
        // act
        var authorizeDirective = new AuthorizeDirective(
            new[] { "a", "b" });

        // assert
        Assert.Null(authorizeDirective.Policy);
        Assert.Collection(authorizeDirective.Roles,
                          t => Assert.Equal("a", t),
                          t => Assert.Equal("b", t));
    }
Exemple #6
0
        public async Task InvokeAsync(IDirectiveContext context)
        {
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();

            ClaimsPrincipal principal     = null;
            var             allowed       = false;
            var             authenticated = false;

            if (context.ContextData.TryGetValue(
                    nameof(ClaimsPrincipal), out var o) &&
                o is ClaimsPrincipal p)
            {
                principal     = p;
                authenticated = allowed =
                    p.Identities.Any(t => t.IsAuthenticated);
            }

            allowed = allowed && IsInAnyRole(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && NeedsPolicyValidation(directive))
            {
                allowed = await AuthorizeWithPolicyAsync(
                    context, directive, principal)
                          .ConfigureAwait(false);
            }
#endif
            if (allowed)
            {
                await _next(context).ConfigureAwait(false);
            }
            else if (context.Result == null)
            {
                context.Result = ErrorBuilder.New()
                                 .SetMessage(
                    AuthResources.AuthorizeMiddleware_NotAuthorized)
                                 .SetCode(authenticated
                        ? ErrorCodes.Authentication.NotAuthorized
                        : ErrorCodes.Authentication.NotAuthenticated)
                                 .SetPath(context.Path)
                                 .AddLocation(context.FieldSelection)
                                 .Build();
            }
        }
Exemple #7
0
    /// <summary>
    /// Authorize current directive using Microsoft.AspNetCore.Authorization.
    /// </summary>
    /// <param name="context">The current middleware context.</param>
    /// <param name="directive">The authorization directive.</param>
    /// <returns>
    /// Returns a value indicating if the current session is authorized to
    /// access the resolver data.
    /// </returns>
    public async ValueTask <AuthorizeResult> AuthorizeAsync(
        IMiddlewareContext context,
        AuthorizeDirective directive)
    {
        if (!TryGetAuthenticatedPrincipal(context, out ClaimsPrincipal? principal))
        {
            return(AuthorizeResult.NotAuthenticated);
        }

        if (IsInAnyRole(principal, directive.Roles))
        {
            if (NeedsPolicyValidation(directive))
            {
                return(await AuthorizeWithPolicyAsync(
                           context, directive, principal !)
                       .ConfigureAwait(false));
            }

            return(AuthorizeResult.Allowed);
        }

        return(AuthorizeResult.NotAllowed);
    }
Exemple #8
0
        private static async Task <bool> AuthorizeWithPolicyAsync(
            IDirectiveContext context,
            AuthorizeDirective directive,
            ClaimsPrincipal principal)
        {
            IServiceProvider      services         = context.Service <IServiceProvider>();
            IAuthorizationService authorizeService =
                services.GetService <IAuthorizationService>();
            IAuthorizationPolicyProvider policyProvider =
                services.GetService <IAuthorizationPolicyProvider>();

            if (authorizeService == null || policyProvider == null)
            {
                return(string.IsNullOrWhiteSpace(directive.Policy));
            }

            AuthorizationPolicy policy = null;

            if (directive.Roles.Count == 0 &&
                string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetDefaultPolicyAsync()
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = context.Result = ErrorBuilder.New()
                                                      .SetMessage(
                        AuthResources.AuthorizeMiddleware_NoDefaultPolicy)
                                                      .SetCode(AuthErrorCodes.NoDefaultPolicy)
                                                      .SetPath(context.Path)
                                                      .AddLocation(context.FieldSelection)
                                                      .Build();
                }
            }

            else if (!string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetPolicyAsync(directive.Policy)
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = ErrorBuilder.New()
                                     .SetMessage(string.Format(
                                                     CultureInfo.InvariantCulture,
                                                     AuthResources.AuthorizeMiddleware_PolicyNotFound,
                                                     directive.Policy))
                                     .SetCode(AuthErrorCodes.PolicyNotFound)
                                     .SetPath(context.Path)
                                     .AddLocation(context.FieldSelection)
                                     .Build();
                }
            }

            if (context.Result == null && policy != null)
            {
                AuthorizationResult result =
                    await authorizeService.AuthorizeAsync(
                        principal, context, policy)
                    .ConfigureAwait(false);

                return(result.Succeeded);
            }

            return(false);
        }
Exemple #9
0
 private static bool NeedsPolicyValidation(
     AuthorizeDirective directive)
 {
     return(directive.Roles.Count == 0 ||
            !string.IsNullOrEmpty(directive.Policy));
 }
Exemple #10
0
 public ValueTask <AuthorizeResult> AuthorizeAsync(
     IMiddlewareContext context,
     AuthorizeDirective directive)
 {
     return(new((AuthorizeResult)context.ContextData["auth"] !));
 }