Securing a path/folder in an ASP.NET Web Application

Create or open your global.asax and open the code behind.

In your Application_AuthenticateRequest method create a request to check if user is logged in and check if his role is entitiled to view the path you are securing. In my case I am using Windows authentication, so I will use User.Identity.Name and if it is null it means no user is logged in. Then we will request the url path the user is requesting to check if the user is trying to access an unauthorized path. If so, we redirect him back to an error page, home page or wherever you prefer.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
try
{

//Check if it contains our secure folder or path part

if (requestPath.Contains(“/Secure/”))

{

//Check if username is null (if null, means not logged in)
if (!string.IsNullOrEmpty(Context.User.Identity.Name))
{

bool allowed = false; // create a statement to see if user is in a role that allows or restricts access to this secure path

//Request URL in browser
string requestPath = Request.Url.AbsolutePath;

//checks if the user does not have access (!allowed means NOT ALLOWED)

if (!allowed)
{

//Redirect to error page

Response.Redirect(“ErrorPage.aspx”);
}

}

}
}
catch (Exception ex)
{

//An exception might occure if the User.Identity.Name is not set (empty / not logged in)
Response.Redirect(“ErrorPage.aspx”);
}

}

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 )

Connecting to %s