CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Redirecting user to NotAuthorized page in Forms Authentication when tried accessing a restricted resource in ASP.Net
Submitted By Satheesh Babu B
On 11/9/2008 5:00:12 AM
Tags: ASP.Net,CodeDigest  

 

When we use forms authentication with roles, the logged in user will be again forwarded to the login page when he/she tries accessing a resource which his/her role is restricted and does not have access.

 

This behaviour does not give a better user experience since the user is already logged in. It will be good if we can redirect the user to "Not Authorized page" with appropriate error message instead of forwading him to the login page.

 

This default behaviour can be prevented and the user can be redirected to NotAuthorized page by adding the below code snippet in the Login Page_Load event.
 
 
protected void Page_Load(object sender, EventArgs e)
    {
if (User.Identity.IsAuthenticated && Request.QueryString["ReturnUrl"] != null)
        {
          
            Response.Redirect("NotAuthorized.aspx");
        }
    }
 

The above code check if the user is already authenticated and has a value in ReturnUrl query string. A value in ReturnUrl query string parameter and with IsAuthenticated flag as true indicates the user is redirected to the login page after he is authenticated and is trying to access a restricted page. We can redirect the user to a Not Authorized page when these conditions are satisfied.

 

That's it! When the above included in the Login.aspx page load event, the user will be automatically redirected to Not Authorized Page when he tries accessing a restricted resource!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..