Redirect to login security example
This is something often asked for. But say you need security to keep people from going to a page bypassing the login screen. In classic ASP you needed to use an include file or the same piece of code on every page and have it check a session varaible or something. No longer do you need this.
I am going to show the easy way first, then I will tell you how to customize it to verify the user from a database.
Step 1: In you web.config file
Code:
<authentication mode="Forms">
<forms loginUrl="webform1.aspx">
<credentials passwordFormat="Clear">
<user name="Chris" password="1234"/>
</credentials>
</forms>
</authentication>
That is the allowable users. I am not going to get into this, but you can encrypt the password with SHA1.
also in the web.config, you need this in the authorization node
Code:
<authorization>
<deny users="?" /> <!-- Allow all users -->
</authorization>
With the combination of those 2 sections, If someone has not logged in, the will be redirected to the page you specify here <forms loginUrl="webform1.aspx">
Now, on your login page, you just put your 2 textboxes for user and password and a button. In the button click code
Code:
If FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text) Then
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, False)
End If
That will verify the user and pass that you put into the web.config. If it is ok, then it will redirect automatically to default.aspx. Now, how do you use this with a databsae? Very simple. just replace the FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text) functiopn with your own function. The RedirectFromLoginpage part is where the actual magic happens and cookies are set. You can make your own REdirectFromLogin function too if you want to customize that , but I wont get into that now.
You may wonder what they False in FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, False)
is for. That lets you specify if you want to save the cookie as a persistant cookie. So what this will let you do is ou can put a checkbox on the login page that is used for 'Remember me' type functionality as seen on other sites, then you can replace the False with checkbox.Value.
I hope this is helpful to you guys in getting some login security easily on your website.
Any Idea on letting them into certain areas
I like the code but I would like to be able to let them go to certain pages but not others. Example: If they login they can go to A, B, and C pages but not D or E unless they login. Redirect D or E if they try to go there???
Is there a value I can Key off of
So in your code is there a value that gets saved somewhere that I can key off of or do I need to write code to hold a value. If so how do you save that value accross pages??
Thanks for any help