Have you ever come across a situation where you want to have multiple login pages with Forms Authentication. Forms Authentication directly supports one login page, but there is a work around. Today we will see how to achieve this.
For an example let’s say you want two login pages where one is for administrators and other is for customers.
When the user clicks on Admin, he should be redirected to administrators’ content where the user will have to authenticate himself as an administrator. When the user clicks on Customer, he will be redirected to customers’ content again where the user will have to authenticate himself as a customer. Administrators login page will have some different content and customers login page will have some other.
|Admin Login Page|
|Customer Login Page|
I have a web application and I have two folders inside my project. One is for Administrators and the other is for Customers. I will create a login page and a sample page inside Admin folder and create another login page and a sample page inside Customer folder. Here is what I have after completing previous steps.
|Folders inside Solution Explorer|
For demonstration purposes in my admin login page I have a drop down where I can select which type of credentials I am going to try in admin login. If login with admin credentials I should be able to see admin content. If I login with customer credentials, I should prompted with admin login again.
|Admin Login Page|
Next I am modifying the global.asax file. I am adding the “Application_AuthenticateRequest” event.
Now I am modifying the “web.config” file as follows.
Now I need to secure directories with role based Forms Authentication. For that again I am modifying the “web.config” file as follows.
As you saw above loginUrl in the forms element can be only one. So I have created a page inside root called “Login” and I am not interested in the design of that page. Just in Page_Load event I am writing the following code. In here what I am doing is, when the main login page is loading it will identify the request type (admin or customer) by analysing the url and redirect to the relevant login page.Now I am all set. In my Default.aspx, I have two hyperlinks for admin content and customer content.
So in the admin login when I logged in with admin credentials I can see the admin content. If I logged in with customer credentials I will be redirected to admin login page again.
|Admin Can View Admin Content|
|Customer Can't View Admin Content|
I am not going to show you how to do this for the customer’s login page. The concept is the same. You can download the sample project from my skydrive and try this out.
Hope this helps.