I need my users are redirected to AuthError.aspx page ("You don't have the access to this page") in the case when they are authenticated but try to access the page that they cannot access (because of the role for exam). If I set up web.config so:
<authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="2880" /> </authentication>
this is the system's wrong behaviour because an user is already authenticated and there is no need to redirect him or her to this page. But if I write here AuthError.aspx instead Login.aspx how could I redirect not-yet-authenticated user to the login page?
Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice. Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.
Authorization refers to the process that determines what a user is able to do. For example, an administrative user is allowed to create a document library, add documents, edit documents, and delete them. A non-administrative user working with the library is only authorized to read the documents.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With