asp.net-mvcrole-based

Role based authentication feed back to user in ASP.NET MVC


I am using role based Authentication for some of the features in my ASP.NET MVC application by implementing

<Authorize(Roles:="Administrator")> _
 Function AdminPage() As ActionResult
    Return View()
  End Function

If the user is not logged in as Administrator this will redirect the user to login page but there is no feed back why it did that. So I want to display a message like "You must be administrator to access this feature."

I am looking for a clean way to do this.

Thank in advance.


Solution

  • You could easily achieve this by writing a custom authorize attribute:

    Public Class CustomAuthorizeAttribute
        Inherits AuthorizeAttribute
        Protected Overrides Sub HandleUnauthorizedRequest(filterContext As AuthorizationContext)
            MyBase.HandleUnauthorizedRequest(filterContext)
            filterContext.Controller.TempData("message") = String.Format("You need to be {0} to access this resource", Me.Roles)
        End Sub
    End Class
    

    And then decorate the controller action with this custom attribute:

    <CustomAuthorize(Roles := "Administrator")> _
    Public Function AdminPage() As ActionResult
        Return View()
    End Function
    

    And somewhere on your Logon View:

    <div><%: TempData("message") %></div>