Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Forms authentication using user names list in web.config - Part 90

Suggested Videos
Part 87 - Windows authentication
Part 88 - Windows authentication and authorization
Part 89 - Windows authentication and folder level authorization

Anonymous authentication is fine for web sites that contain public information that every one can see. We discussed about Anonymous authentication in
Part 85 - Anonymous authentication
Part 86 - Anonymous authentication and impersonation

Windows authentication is used for intranet web applications, where the users are part of a windows domain-based network. We discussed about Windows authentication in Parts 87, 88 and 89.



In this video we will discuss about
1. When to use Forms Authentication
2. How to enable Forms Authentication

When to use Forms Authentication?
Forms authentication is used for internet web applications. The advantage of Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Many internet web sites like Gmail.com, Amazon.com, facebook.com etc uses forms authentication. To access these applications we do not have to be member of their domain-based network.



How to enable Forms Authentication?
Create an asp.net web application project. Add a webform with name Welcome.aspx, and Login.aspx. Add a new folder with name "Registration", to the project. Add Register.aspx web form to the "Registration" folder.

Welcome.aspx HTML:
<h1>Welcome Page</h1>

Login.aspx HTML:
<div style="font-family:Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>Login</b>
        </td>
    </tr>
    <tr>
        <td>
            User Name
        </td>    
        <td>
            :<asp:TextBox ID="txtUserName" runat="server">
            </asp:TextBox>
        </td>    
    </tr>
    <tr>
        <td>
            Password
        </td>    
        <td>
            :<asp:TextBox ID="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>
        </td>    
    </tr>
    <tr>
        <td>
                    
        </td>    
        <td>
            <asp:Button ID="btnLogin" runat="server" Text="Login" />
        </td>    
    </tr>
</table>
<br />
<a href="Registration/Register.aspx">Click here to register</a> 
if you do not have a user name and password.
</div>

Register.aspx HTML:
<h1>Registration Page</h1>

If you run the application now, we will be able to navigate to any page, just by changing the name of the page in the address bar. We are not logged in, but we are still able to access all the pages in the application. 

Let us enable forms authentication now. To enable forms authentication, set authentication element's mode attribute to forms in web.config file of the application. 
<authentication mode="Forms">
   <forms loginUrl="Login.aspx" timeout="30" 
          defaultUrl="Welcome.aspx" protection="All">
    <credentials passwordFormat="Clear">
      <user name="venkat" password="venkat"/>
      <user name="pragim" password="pragim"/>
      <user name="prasad" password="prasad"/>
    </credentials>
  </forms>
</authentication>

<authorization>
  <deny users="?" />
</authorization>

The description of the attributes
loginUrl - The URL of the login Page

timeout - Specifies the number of minutes the authentication cookie persists on the clients’s computer. The default is 30 minutes.
  
defaultUrl - The url the user will be redirected after authentication

Protection - Specifies the protection for authentication cookie stored on the clients’s computer. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.

Double click the login button on the Login.aspx page. Copy and paste the following code in the button click event handler.
// Authenticate againts the list stored in web.config
if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text))
{
    // Create the authentication cookie and redirect the user to welcome page
    FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkBoxRememberMe.Checked);
}
else
{
    lblMessage.Text = "Invalid UserName and/or password";
}

Run the application. Try to navigate to Welcome.aspx or Registration/Register.aspx pages, you will be redirected to Login page. After you login, you will be able to access these pages. 

There are 2 problems with this application at the moment.
1. It is not a good practise to store user names and passwords in web.config file. If you want to create the user names and passwords dynamically, you need to change the web.config file. If you change the web.config file at run time, the application restarts and all the session data will be lost, if stored inside the worker process. In a later video session, we will discuss about storing user names and passwords in a database table.

2. At the moment, users are not able to access Register.aspx page, if they are not logged in. If a user does not have user name and password, he should be able to register himself using Register.aspx page. In a later video session, we will discuss about this.

16 comments:

  1. I tried this exactly as you have it and I get a lot of errors
    It keeps saying that it can't find the schema for the attributes that are in the web.config file

    ReplyDelete
  2. FormsAuthentication dose not exist in the current context. please help . Regards, Abdul Waheed

    ReplyDelete
    Replies
    1. Did u add system.web.security namespace to the form.?
      Add and then check...

      Delete
  3. where is FormAuthentication class created

    ReplyDelete
  4. hi, i have added system.web.security yet i still get errors, i have all the ones that you have in the vid, i get this error
    'System.Web.Security.FormsAuthentication.Authenticate(string, string)' is obsolete: 'The recommended alternative is to use the Membership APIs, such as Membership.ValidateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.'
    followed by
    The name 'chkBoxRememberMe' does not exist in the current context
    The name 'lblMessage' does not exist in the current context
    any help is greatly appreciated.

    ReplyDelete
    Replies
    1. Add Label and checkbox.Remove the text of label.Set label id lblMessage and check box id chkBoxRememberMe.

      Delete
  5. deny users=? does not deny access to anonymous users

    ReplyDelete
  6. Hello. I am trying to develop a website where authors can submit research papers which will be first reviewed by the reviewers so there are 2 types of roles in my website i want to restrict users of one role to visit pages of 2nd role and vice versa.

    ReplyDelete
  7. This problem occurs when you have created the new project as empty website which through this unexpected error even you have assembly reference and namespace included.
    Better to do is that create a new project other than empty Asp.NET website than remove all the folders and related pages expect assembly references and update web.config file as per require.
    Hope it will help you.

    ReplyDelete
  8. hi, i have added system.web.security yet i still get errors, i have all the ones that you have in the vid, i get this error
    'System.Web.Security.FormsAuthentication.Authenticate(string, string)' is obsolete: 'The recommended alternative is to use the Membership APIs, such as Membership.ValidateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.'

    ReplyDelete
  9. I think I missed something. I know you are redirecting to Welcome.aspx upon successful login where you include the value for chkBoxRememberMe in the querystring. I don't think you ever completed the development of Welcome.asp. I am curious about what you do with the value for chkBoxRememberMe. Do you save the user's credentials in a cookie? What happens on login.aspx when the user's credentials were saved in a cookie? Does that user go automatically to the Welcome.aspx page? Did I missed the video where you demonstrate this development?

    ReplyDelete
  10. When creating project, if select empty project than it's working fine, but when select webform project and run gives a server error access is denied. Anyone give me this solution i'm using visual studio 2017

    ReplyDelete
  11. I am trying to use your approach to my project. Once I set in web config I can no longer run the project (the startup page is Login.aspx) because the startup page is denied access....

    ReplyDelete
  12. Yeah sir anonymous users can easily penetrate our website it's not working
    Deny users="?"

    ReplyDelete
  13. We get Access Denied in VisualStudio 2017/2019. To prevent error, we need disable UserFriendlyNames module - to do this, we can comment row RouteConfig.RegisterRoutes(RouteTable.Routes) row in Global.asax file or instead delete .aspx extension in defaultUrl and in LoginUrl in Web.config.

    ReplyDelete

It would be great if you can help share these free resources