When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
Technology Jobs
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.
Published: Wednesday, October 31, 2001

Using Forms Authentication in ASP.NET, Part 3

By Darren Neimke


  • Read Part 1
  • Read Part 2

  • - continued -

    '

    In Part 2 we looked at configuring forms authentication, protecting certain areas of a Web site through the authorization tag in Web.config, and how to implement forms authentication for a scenario where user credentials were stored in a database table. In this part, we'll look at how these credentials can be stored in Web.config; also, we'll wrap up this article by discussing some various helpful tips when using forms authentication in ASP.NET.

    Specifying User Credentials in Web.config
    ASP.NET also allows you to define your login credentials in the Web.config file and Authenticate against them using the Authenticate() method of the FormsAuthentication provider. To demonstrate this we will first set up a set of credentials in the config file like so:

    ' web.config file    
    <configuration>
        <system.web>
           
        <authentication mode="Forms">
        <forms loginUrl="MyLoginPage.aspx">
            <credentials passwordFormat="Clear">
                <user name="Darren" password="foobar" />
            </credentials>
        </forms>
        </authentication>
              
        <authorization>
        </system.web>
    </configuration>
    

    Then when authenticating you simply call Authenticate, passing in the Username and Password: (the example below omits the server-side script block and form for brevity...)

    If FormsAuthentication.Authenticate (txtUserName.Text, txtPassword.Text) Then    
        FormsAuthentication.RedirectFromLoginPage (UserName.Text, False)
    Else
        Invalid credentials supplied, display message
        lblMessage.Text = "Invalid login credentials"
    End If    
    

    Although ASP.NET applications can be secured using credentials stored in the Web.config file, you would obviously only use this method for a site where you had a relatively small number of users. For larger sites it makes sense to keep authentication credentials stored in a database and use the Custom validation method to validate unauthenticated incoming requests.

    The Authentication Cookie
    By default the RedirectFromLoginPage method issues a temporary cookie that expires when the browser is closed. This cookie can be made to persist for 50 years by passing True as the second argument of this method.

    To demonstrate how a developer would implement this, let's imagine that we have a Checkbox on our login form with the ID of chkPersistCookie. This checkbox could be used to allow the user to optionally persist the cookie across multiple visits to the site, thus saving them from having to login each time they visit. We could easily persist the cookie by simply passing in the value of chkPersistCookie as the second parameter to RedirectFromLoginPage(), like so:

    If FormsAuthentication.Authenticate (txtUserName.Text, txtPassword.Text) Then    
        FormsAuthentication.RedirectFromLoginPage (UserName.Text, chkPersistCookie.Checked)
    Else
        Invalid credentials supplied, display message
        lblMessage.Text = "Invalid login credentials"
    End If    
    

    As you can see, if the Checkbox is checked then True will be passed and the Cookie will be stored on the users machine, otherwise False will be passed and the Cookie will be issued as a Session Cookie and expire when the user closes his/her browser.

    Creating a Cookie with a custom Expiry Date
    Alternatively you can create a cookie that's issued and has a custom lifetime instead of 50 years. The key is to replace the call to RedirectFromLoginPage method with the your own implementation, like so:

    Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie (UserName.Text, _
                            chkPersistCookie.Checked)
    ' Expires in 30 days, 12 hours and 30 minutes from today.
    cookie.Expires = DateTime.Now.Add(New TimeSpan(30, 12, 30, 0))
    Response.Cookies.Add (cookie)
    Response.Redirect (FormsAuthentication.GetRedirectUrl (UserName.Text, _
                            chkPersistCookie.Checked))  
    

    Here we have created a new authentication cookie, explicitly set its expiration date, added the cookie to the Cookies collection of the current HttpResponse instance, and finally we redirect the user to the page that they had requested.

    Determining the Username of the Logged-On User
    There are oftentimes when an authenticated user visits a page that you'd like to be able to determine who, exactly, the authenticated user is. For example, if you were creating content customized to the user, you'd most certainly be interested in the username of the user visiting your page. ASP.NET makes it easy to determine this information. All you have to do is read the User.Identity.Name property. If, on an ASP.NET Web page, you output this property and the visitor is an unauthenticated user, an empty string will be returned and displayed. If, however, the user has been authenticated, then the property will return the unique username you specified in the first parameter of the RedirectFromLoginPage() method.

    Summary
    Hopefully you can see that the Forms Authentication Provider though it's Static methods has greatly simplified the amount of code that needs to be written for menial and repetitive tasks such as Checking for Authentication, Creating a Cookie and Re-Directing after authentication.

    Happy Programming!

  • By Darren Neimke



  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article