Asp.Net Core policy based authorization ends with 401 Unauthorized

后端 未结 1 1306
野的像风
野的像风 2020-12-19 16:11

I am working on setting up a skeleton of custom policy based authorization which will have a set of business rules to authorized the currently logged on user. But, currently

相关标签:
1条回答
  • 2020-12-19 16:48

    That is because the AuthorizeFilter added to the pipeline for every [Authorize] attribute requires users to be authenticated.

    If you look at the source code, you will see that even without calling any policy it is making sure the user is authenticated:

    // Note: Default Anonymous User is new ClaimsPrincipal(new ClaimsIdentity())
    if (httpContext.User == null ||
        !httpContext.User.Identities.Any(i => i.IsAuthenticated) ||
        !await authService.AuthorizeAsync(httpContext.User, context, Policy))
    {
        context.Result = new ChallengeResult(Policy.AuthenticationSchemes.ToArray());
    }
    

    That condition httpContext.User.Identities.Any(i => i.IsAuthenticated) will be false for anonymous users.

    • There is also a DefaultPolicy in the AuthorizationOptions that verifies the user is authenticated. You can set that as null in the AddAuthorization configuration, but even in this case the AuthorizeFilter above will make sure the user is authenticated

    The easiest way just for you to try your code would be adding an authenticated anonymous user, so any anonymous user gets assigned a ClaimsPrincipal that is authenticated (as it has a GenericIdentity instead of an empty ClaimsIdentity):

    //Add this before app.UseMvc
    app.Use(async (context, next) =>
    {
        if (!context.User.Identities.Any(i => i.IsAuthenticated))
        {
            //Assign all anonymous users the same generic identity, which is authenticated
            context.User = new ClaimsPrincipal(new GenericIdentity("anonymous"));
        }
        await next.Invoke();
    
    });
    

    In a real app you will probably have some authentication framework where users can authenticate themselves, so you wouldn't have this problem.

    Otherwise you might need to play with the application conventions, and replace the AuthorizeFilter with your own tweaked implementation that doesn't require authenticated users, this answer goes in that direction.

    0 讨论(0)
提交回复
热议问题