Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0 Redirecting user from AuthorizationHandler, HandleRequirementAsync method

I am trying to implement AuthorizationHandler in .net core 2.0 where i need to authorize the user and based on the condition wanted to redirect to different action methods within my application validation works ok but how i can redirect user to the Access Denied or Login page when authorization failed.

 protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasPermissionRequirement requirement)
    {
        var controllerContext = context.Resource as AuthorizationFilterContext;

        if (sessionManager.Session.sysUserID <= 0)
        {
            controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login", area = "" }));

            return Task.FromResult(0);
        }


            if (Utilities.GetInt32Negative(PermissionID) == 1 || Utilities.GetInt32Negative(PermissionID) == -1)
            {
                if (!PagePath.Equals("~/"))
                    controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "NoAccess", area = "" }));
            }

            context.Succeed(requirement);
        }
        else
        {
            if (!PagePath.Equals("~/"))
                controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "NoAccess", area = "" }));
        }

        return Task.FromResult(0);
    }
like image 553
Azhar Avatar asked Dec 03 '22 21:12

Azhar


1 Answers

I found the solution and i hope this will help someone looking for the similar, in custom authorization we can redirect to any desired controller action using the AuthorizationFilterContext and with the RedirectToActionResult

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasPermissionRequirement requirement)
{
    // Get the context       
    var redirectContext = context.Resource as AuthorizationFilterContext;
    //check the condition 
    if (!result)
    {
        redirectContext.Result = new RedirectToActionResult("AccessDenied", "Home", null);
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
    context.Succeed(requirement);
    return Task.CompletedTask;
}
like image 146
Azhar Avatar answered Dec 06 '22 10:12

Azhar