Reputation: 37905
I am using claim based authentication and authorization in aspnetcore 1.1.
If the user is not logged in, he gets fowarded to the login page as expected.
However, if the user is logged in, but does not have the correct claim, the user is forwarded back to the login page again.
How do I change that so it the user is routed to a different view which says "You are not authorized..."?
services.AddAuthorization(options=>
{
options.AddPolicy("IsEDIAdmin", policy =>
policy.RequireClaim("IsEDIAdmin"));
});
[Authorize(Policy = "IsEDIAdmin")]
public IActionResult App()
{
return PartialView();
}
Upvotes: 2
Views: 708
Reputation: 118937
I think it's a bit more complicated than it should be, but you should be able to create your own filter. For example (not tested but compiles):
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claim, string failUrl) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] { claim, failUrl };
}
}
public class ClaimRequirementFilter : IAsyncActionFilter
{
private readonly string _claim;
private readonly string _failUrl;
public ClaimRequirementFilter(string claim, string failUrl)
{
_claim = claim;
_failUrl = failUrl;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.User.Claims.Any(c => c.Value == _claim))
{
context.Result = new RedirectResult(_failUrl);
}
else
{
await next();
}
}
}
And use it like this:
[ClaimRequirement("IsEDIAdmin", "/some-exciting/url")]
public IActionResult Index()
{
//snip
}
Upvotes: 1