How to Redirect Users to an ASP.NET page when not Authorized? How to Redirect Users to an ASP.NET page when not Authorized? asp.net asp.net

How to Redirect Users to an ASP.NET page when not Authorized?


On the Page_Load of your login page, you'll want to check if the user is authenticated, and if they are to redirect them to your access denied page:

protected void Page_Load(object sender, EventArgs e){    if (User.Identity.IsAuthenticated) // if the user is already logged in    {            Response.Redirect("~/AccessDenied.aspx");    }}

If you want to get a little fancier, you can check the ReturnUrl parameter to determine if the user came to the page directly (such as through a bookmark they saved right to the login page) and handle that differently. Here's an example:

protected void Page_Load(object sender, EventArgs e)    {        if (User.Identity.IsAuthenticated)        {            // if they came to the page directly, ReturnUrl will be null.            if (String.IsNullOrEmpty(Request["ReturnUrl"]))            {                 /* in that case, instead of redirecting, I hide the login                     controls and instead display a message saying that are                     already logged in. */            }            else            {            Response.Redirect("~/AccessDenied.aspx");            }        }    }


For me the least hassle most benefit solution to this problem was to create another section (panel) in Login.aspx page with contents to be displayed to users who are authenticated (e.g. logged in) saying "Access denied" instead of the login form. When logged in user hits the page it means they most likely ended up here because they are not authenticated to access the page that redirected them here.

In the login page I use this very simple code to switch visibility of the panel and login form:

if (Request.IsAuthenticated){    LoginUser.Visible = false;    AccessDeniedPanel.Visible = true;}

It's dead simple and it works.


You need to:

1) enable roles (in web.config): (replace 'xxx' with your own values)

<roleManager enabled="true">  <providers>    <clear />    <add connectionStringName="ApplicationServices" applicationName="xxx"      name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />    <add applicationName="xxx" name="AspNetWindowsTokenRoleProvider"      type="System.Web.Security.WindowsTokenRoleProvider" />  </providers></roleManager>

2) you need to restrict access to certain areas of your website for specific roles.I actually answered another question today where I explain how to achieve this.Here is the link