views:

561

answers:

2

In my ASP.NET MVC app, I have most controllers decorated with

[Authorize(Roles="SomeGroup")]

When a user is not authorized to access something, they are sent to "~/Login" which is the Login action on my Account controller.

How can I determine that a user has reached the login page because of not being authorized so that I can show an appropriate error?

+5  A: 

You can look for the ?ReturnUrl= querystring value, or you can create your own authorization filter & set a field in TempData indicating the reason.

Here is a simple custom filter that will do the trick:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private bool _isAuthorized;

    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        _isAuthorized = base.AuthorizeCore(httpContext);
        return _isAuthorized;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if(!_isAuthorized)
        {
            filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
        }
    }
}

Then in your view, you can do something like this:

<% if(TempData["RedirectReason"] == "Unauthorized") { %>
    <b>You don't have permission to access that area</b>
<% } %>

(Though I'd recommend a better approach than these magic strings, but you get the point)

Ben Scheirman
Easy to implement and it works. Thanks.
Ronnie Overby
Thanks Ben, I implement the same on my side and work very well!
Gabriel Mongeon
A: 

still can't get it.How to use the class and which view will be changed.

Ashish