Home About Us SQL Interview Book Contact Us RSS
Articles
Tools
Code Snippets
Links
Tips & Tricks
FAQ
Resources
Articles
Code Snippets
Links
FAQ
Resources

Saravana Kumar
Vinod Kumar


SignOn using Forms Authentication

             In this code snippet, I am going to explain how you can create SignOn screen when you have Forms Authentication. For forms authentication you need to set two settings in Web.Config file. First things is setting authentication tag,

                          <authentication mode= "Forms">
                                      <forms  name=".ASPXAUTH"  
                                                 loginUrl="login.aspx"
                                                 protection="all"  
                                                 timeout="30"
                                                 path="/"   />
                           </authentication>
 
Next thing you should set is, authorization tag.
                           <authorization>
                                   <deny users="?" />
                           </authorization>
 
                After setting these two things, User will be automatically redirected to login page if they are not authenticated. So in the login page you need to have two text boxes for getting username and password and one button which does authentication. When you do postback, you need to have following code in button click event handler for doing forms authentication.
 
Private Sub butSignOn_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles butSignOn.Click
    ' Authenticate username/password from <credentials>.
   ' Instead of this method, you can call you own api for authentication which return boolean after authenticating user.
    If FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text) _
         Then
        ' If found, display the application's Start page.
        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True)
    Else
        ' Otherwise, clear the password.
        txtPassword.Text = ""
        ' If third try, display "Access Denied" page.
        If CInt(ViewState("Tries")) > 1 Then
            Response.Redirect("Denied.htm")
        Else
            ' Otherwise, increment number of tries.
            ViewState("Tries") = CInt(ViewState("Tries")) + 1
        End If
    End If
End Sub
 
I think comments inside this codesnippet will explain you what is the use of each method used here. For more details refer this artilce - How to implement Forms Authentication in your ASP.NET Application using VB.NET