Asp.Net Core policy based authorization ends with 401 Unauthorized

落花浮王杯 提交于 2019-11-29 11:24:50
Daniel J.G.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!