Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Policy based Authorization not working in asp.net core

I'm trying to get Policy based Authorization working in .net core 2.1 based on this article: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1

However I cannot seem to get it to fire.

In the below example, I've commented out the context.suceeed line, so I would have thought my api call to my usercontroller would fail.

However my API call is being accepted.

What am I doing wrong?

This is my startup.cs

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddSingleton<IAuthorizationHandler, VerifyAuthCookieHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("VerifyAuthCookie", policy =>
                policy.Requirements.Add(new VerifyAuthCookieRequirement()));
        });

        services.AddMvcCore().AddJsonFormatters();

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMvc();
    }

}

Here is my handler

public class VerifyAuthCookieHandler : AuthorizationHandler<VerifyAuthCookieRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   VerifyAuthCookieRequirement requirement)
    {

        //context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

And here is my requirement:

public class VerifyAuthCookieRequirement : IAuthorizationRequirement
{

    public VerifyAuthCookieRequirement()
    {

    }
}

And finally, my controller:

[Route("api/[controller]")]
[Authorize(Policy = "VerifyAuthCookie")]
public class UserController : Controller
{

}

If I add code in HandleRequirementAsync and set a breakpoint then it's not being hit when I debug, so my Handler doesn't appear to be called at all.

like image 685
Robbie Mills Avatar asked Jun 11 '18 07:06

Robbie Mills


2 Answers

You should call app.UseAuthentication(); before the app.UseMvc(); in the Configure method of the Startup class. This will add the ASP.NET Core authentication middleware to the request pipeline.

Since you are using services.AddMvcCore() we'll need to configure the authorization services manually, something services.AddMvc() does for you automatically. We should add .AddAuthorization() to the IMvcCoreBuilder. This will add the default Authentication- and Authorization services and a PolicyEvaluator.

If you're interested in the exact services that will be registered in your DI container you should follow this link.

like image 97
user1336 Avatar answered Oct 20 '22 00:10

user1336


I had similar issue, I fix it by :

services.AddMvcCore().AddAuthorization().AddJsonFormatters();

like image 40
tsuryadi Avatar answered Oct 20 '22 01:10

tsuryadi