0

I have successfully implemented group based authorization in an MVC application by using the [Authorize(Roles = "Admin")] tags in my controller.

However, the default behaviour when a user requests a page they are not authorized to view is to redirect them to the login page. This far from intuitive, and causes too much confusion amongst users who will repeatedly try to login.

Instead I would like to display a custom screen, or at the very least have a message display on the login screen stating that they are already logged in, but with insufficient privileges.

A User.Identity.IsAuthenticated tag exists, which can be used in the base logic, but there doesn't appear to be a similar IsAuthorised tag.

How can this behaviour be implemented?

Gavin Coates
  • 1,366
  • 1
  • 20
  • 44

1 Answers1

0

I believe you have already partly solved your problem. This because because when authorization fails, the user will be redirected to login page. Verify if the user is authenticated before displaying the login view. If they are authenticated re-direct them to appropriate page instead.The code snippet below will not display login view if the user is authenticated and the cookie has not expired. They will be redirected to "DashboardOrSomeOtherView.cshtml" instead

    [HttpGet]
    public ActionResult Login(string returnUrl)
    {
        // Before showing login view check if user is authenticated. 
        // If they are redirect to suitable page, 
        // and print appropriate message
        if (ControllerContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // You can even use TempData as additionally, to hold data here and check in 
            //the view you redirect to if it is not null and is true , 
            // then they are authenticated and show some message, 
            // e.g. You have been redirected here because you do not 
            // have authorization to view previous page.

            TempData["UserAlreadyAuthicated"] = true;
            return RedirectToAction("DashboardOrSomeOtherView");
        }

         // If they are not authenticated , show them login view
        return View();
    }

In the DashboardOrSomeOtherView

<div>
 <h1>DashboardOrSomeOtherView</h1>
  @{
    if(TempData["UserAlreadyAuthicated"] != null && TempData["UserAlreadyAuthicated"].ToString().ToLower() == "true")
     <div>You have been redirected here because of inadequate authorization</div>
   }
</div>
Julius Depulla
  • 1,493
  • 1
  • 12
  • 27