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 the skeleton always ends up with 401 Unauthorized.
Here is my code,
public class MyAuthorizationRequirement : IAuthorizationRequirement
{
public MyAuthorizationRequirement()
{
}
}
public class MyAuthorizationHandler : AuthorizationHandler<MyAuthorizationRequirement>
{
public MyAuthorizationHandler()
{
}
protected override void Handle(AuthorizationContext context, MyAuthorizationRequirement requirement)
{
context.Succeed(requirement);
}
}
And following in the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>()
.AddAuthorization(options =>
{
options.AddPolicy("MyAuthorization",
policy => policy.Requirements.Add(new MyAuthorizationRequirement()));
});
}
And this is how I use it in my HomeController (MVC 6)
[Authorize(Policy = "MyAuthorization")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
When I don't put the Authorize attribute, the Index view renders fine. But, when I include the Authorize attribute, I just receive the blank view. And when I check the developer tools (Network) I get the following behind the scene details.
Request URL:http://localhost:51129/
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:51129
The breakpoints to the constructors of my requirement and handler classes are invoked, but the breakpoints to the Handle method of Handler class, and Index method of Controller class never get invoked.