MVC Action Authroization

One good option to apply the action level authorization is to subclass the “AuthorizeAttribute” and in the “AuthorizeCore” method, check for user authorization. If we are using the “Form” authentication then simply we can return “false” and it will redirect the user to the Login Form. In case of windows authentication and running on IIS, it will just keep displaying the Windows Login dialog to the user, so it is better to redirect the user to an Error View for windows Authentication.

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class AuthorizeAction : AuthorizeAttribute
{
    private int currAction;

    public AuthorizeAction( int currAction )
    {
        this.currAction = currAction;
    }

    protected override bool AuthorizeCore( HttpContextBase httpContext )
    {
        //check "currAction" against custom database user authroization and set the allowed variable
	bool allowed = true;

	//if user is not authanticated then return the error
        if ( !httpContext.User.Identity.IsAuthenticated )
            allowed = false;

        if ( ! allowed )
        {
            //if it's an AJAX call then simply return the error to the client and show error dialog there
            if ( !string.IsNullOrEmpty( httpContext.Request.Headers["X-Requested-With"] ) && httpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest" )
                return false;
            else
            {
                //in case of a normal URL access, redirect to the special error controller/action.
                httpContext.Response.Redirect( "~/Error/UnAuthorized/" );
                return true;
            }
        }
        else
        {
            return true;
        }
    }
}
Advertisements

Tags: ,

About prres

I have been working with Microsoft Tools and Technologies for 9 years. Most of my work include architecting and developing with C#, ASP.Net, Silverlight and SQL Server.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: