Say you are using Forms Authentication and have set up authorization in your web.config to allow access to particular users or roles and/or denying anonymous access.
1: Deny Anonymous users:When an unauthenticated user tries to access a secured page, by its default behavior users will be redirect to your login page or I should say the loginUrl set in the forms element of your web.config.
2: Allow certain Roles: Now say if a user is already authenticated and tries to access a page allowed only to the users in particular role e.g. "admin", you will see the same behavior as for anoymous users above. The authenticated user is redirected to login page.
In second case, most of the time, it makes sense to redirect unauthorized users to a different page that displays appropriate message like "Access Denied".
The first idea would be to use customErrors element in the web.config.
<customErrors mode="On" defaultRedirect="~/GenericErrorPage.htm" >
<error statusCode="401" redirect="~/unauthorized.htm"/>
But that won't work becuase the FormsAuthenticationModule modifies the 401 status to 302 redirect status and redirects the user to login page. For more detailed information check here.
1: Add and design a page (e.g. "unauthorized.aspx") with appropriate access denied message.
2: Add this code to the Page_Load of your login page. (Note: Originally discussed here)
protected void Page_Load(object sender, EventArgs e)
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))Response.Redirect("~/unauthorized.aspx");