Reputation: 389
In a ASP.NET Core 2 MVC app, I had a custom AuthorizationHandler
that redirected blocked users back to the home page.
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAllowedIpAddressRequirement requirement)
{
// Cast the context resource
if (context.Resource is AuthorizationFilterContext cxt)
{
// Failed!
cxt.Result = new RedirectToActionResult("Index", "Home", new { msg = "Your auth has failed." });
context.Succeed(requirement);
}
...
}
Since migrating to ASP.NET Core 3.1, the context is an object of class Microsoft.AspNetCore.Routing.RouteEndpoint
, which has no Result
property.
How can I redirect the user to a specific page?
Upvotes: 1
Views: 1687
Reputation: 261
I had the same problem and to solve it I changed to Filter (IAsyncResourceFilter
) instead of Policy.
You can wrap your authorization logic into a policy and then invoke the IAuthorizationService and redirect anywhere/anytime you need.
Example:
public class MySampleActionFilter: IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//if failed
context.Result = new RedirectToRouteResult(new RouteValueDictonary(new
{
controller = "Your Controller",
action = "Your Action"
}));
}
}
By the way, this is for .net Core 3 and above
Upvotes: 2
Reputation: 195
if you want to user redirect to some page like login page, if user didn't has access, you could following below steps for fix it:
into HandleRequirementAsync
method
if (Condition())
{
context.Succeed(requirement);
}
else {
context.Fail();
}
if user did has access, execute context.Succeed(requirement);
and if user didn't has access, execute context.Fail();
into startup.cs
=> ConfigureServices
method
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(12);
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});
in line that we write
options.LoginPath = "/Account/Login";
we appointment users after failing in HandleRequirementAsync
method for checking access, being redirected to controller 'home' controller and 'login' actiion.
i'll hope my answer be useful for friends.
Upvotes: 1