惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
博客园 - 司徒正美
美团技术团队
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Troy Hunt's Blog
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
Cisco Talos Blog
Cisco Talos Blog
T
Tor Project blog
B
Blog
NISL@THU
NISL@THU
月光博客
月光博客
博客园 - 【当耐特】
AWS News Blog
AWS News Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
腾讯CDC
L
Lohrmann on Cybersecurity
The Cloudflare Blog
L
LINUX DO - 最新话题
S
Security @ Cisco Blogs
S
Secure Thoughts
Spread Privacy
Spread Privacy
有赞技术团队
有赞技术团队
The Last Watchdog
The Last Watchdog
Project Zero
Project Zero
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
H
Hacker News: Front Page
S
SegmentFault 最新的问题
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
P
Privacy & Cybersecurity Law Blog
博客园 - 三生石上(FineUI控件)
Forbes - Security
Forbes - Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
InfoQ
T
Tailwind CSS Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
G
GRAHAM CLULEY
W
WeLiveSecurity
小众软件
小众软件
Recorded Future
Recorded Future
Cyberwarzone
Cyberwarzone
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

博客园 - XXXCccddd

数据库SQL的效率 javascript去空格函数 精妙SQL语句 在AS.net中实现单点登陆 Session操作 Server.Transfer 和 Response.Redirect 区别 vs.net web项目使用visual source safe进行源代码管理 数据库设计规范 常用函数表 xmlhttp实现无刷新页面 XP风格样式表 Using Forms Authentication in ASP.NET - Part 2 如何关闭系统所有Excel进程 [转]每一项都是js中的小技巧,但十分的实用! asp.net中常用的一些小技巧 ASP.NET开发经验积累(转) Visual SourceSafe应用守则(转) 应用系统架构设计-补全篇(转) 系统设计说明书(架构、概要、详细)目录结构
Using Forms Authentication in ASP.NET - Part 1
XXXCccddd · 2005-11-21 · via 博客园 - XXXCccddd

Introduction

Classic ASP developers often had to "roll their own" authentication scheme, however, in ASP.NET much of the grunt work has been taken out. This article outlines how things have changed and how FormsAuthentication can be used to secure a Web site with a minimal amount of code.

In classic ASP, authentication was pretty much all or nothing. Either you were using integrated security (often referred to as the Microsoft Windows NT LAN Manager [NTLM] challenge/response authentication protocol ), Basic (referred to as clear text), or you had created your own type of authentication. This was often an arduous task. Forms Authentication allows developers to store the authentication information, such as username and password, in the Web.config file, or you can still use your own method, such as a database, eXtensible Markup Language (XML) file, or text file. The great thing about forms authentication is you no longer have to program the state-tracking portion. ASP.NET does it for you!

  • download source code
  • view demo
  • Forms Authentication Background

    Forms authentication uses cookies to allow applications to track users throughout their visit. The way ASP.NET handles forms authentication is probably very similar to the methods you have used in classic ASP. When a user logs in via forms authentication, a cookie is created and used to track the user throughout the site. If the user requests a page that is secure and has not logged in, then the user will be redirected to the login page. Once the user has been successfully authenticated, he/she will be redirected to their originally requested page.

    Standard Forms Authentication Setup

    Pages used: Default.aspx, Login.aspx, Web.config

    In the standard method of Forms Authentication, all user information is stored in the Web.config.

    Create a folder named standardForms under your webroot.

    Make this folder an application inside the Internet Services Manager. (This should be familiar territory if you ever used the Global.asa in ASP.)

    Web.config Overview

    The Web.config contains all of the configuration settings for an ASP.NET application. The idea is to put the control of the Web application in the hands of the developer rather than the system administrator. There are lots of options you can use here. This article details only the ones specific to Forms Authentication today.

    Web.config Code Using the Standard or "Credentials" Method

    Authentication

    Attributes

    Description

    Name

    This is the name of the cookie used for authentication. NOTE: If multiple applications want to use FormsAuthentication on the same machine, it is best to use unique names.

    Path

    Path used for cookie. The default value "/" often avoids errors with incorrect case in paths, since browsers are strictly case-sensitive when it comes to returning cookies.

    LoginUrl

    URL that unauthenticated users are redirected to.

    Protection

    Method used to protect cookie data. Default and suggested value is "All," which does validation and encryption.

    Timeout

    Number of minutes until authentication cookie expires.

    Credentials

    Attributes

    Description

    passwordFormat

    Format the password will be stored in. Valid values include Clear, SHA1, and MD5. SHA1 and MD5 are both hashing algorithms that make storing passwords in the Web.config more secure.

    User

    This is the area to store the username and password. You can secure the passwords by running the HashPasswordForStoringInConfigFile function to get the hashed password. I will demonstrate this later.

    Authorization

    Attributes

    Description

    Deny | Allow

    This section allows us to deny or allow users to the site. ? = anonymous/unauthenticated users and * means all users. This section also allows us to specify certain users, and allow or deny permissions.

    Web.config Code

    
    <configuration>
        <system.web>
            <customErrors mode="Off"/>
            <authentication mode="Forms">
                <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30">
                    <credentials passwordFormat="Clear">
                        <user name="jeff" password="test" />
                        <user name="mike" password="test" />
                    </credentials>
                </forms>
            </authentication>
            <authorization>
                <deny users="?" />
            </authorization>
        </system.web>
    </configuration>
    
    

    Web.config Details

    Inside the Web.config above we have configured several options.

    Authentication
    The mode attribute for the <authentication> configuration section sets the authentication mode to Forms. Inside the <forms> section we are assigning the name attribute to "AppNameAuth". You might want to change the name of the cookie to something like "HRWebAuth", where HRWeb is the name of your application.

    Remember, if you are going to have multiple applications on the same machine, it's suggested that you use unique names for your cookies.

    Next, we set the path to the root of the application. We assign the loginUrl attribute a local page named loginUrl.aspx. You can use URL paths like https://secured.sumnurv.com for redirection as well. Setting protection to all is the suggested value. This means that the cookie will be both encrypted (using the Triple DES data-encryption standard) and validated.

    The validation algorithm comes from the machineKey element located in Machine.config. This data validation ensures that the cookie data wasn't tampered with during transit (someone sniffing traffic and responding with modified cookie).

    The timeout attribute refers to the number of minutes before a cookie expires and the user must log in again. In the credentials section, we add two users and their passwords. This is where FormsAuthentication will look to authenticate the users.

    Authorization
    In the authorization section, we want to ensure that no unauthenticated users can access the application. The "?" means anonymous users, so we set a deny flag for all anonymous users.

    Login.aspx Overview

    All user authentication logic is performed here. If you wish to verify a user's credentials against the Web.config, XML or text file, or database, this is the place it would happen. This example shows how to authenticate to the Web.config

    Login.aspx Code

    
    <%@Page Language="VB" %>
    <%@Import Namespace="System.Web.Security" %>
    <script language="VB" runat="server">
    Sub ProcessLogin(objSender As Object, objArgs As EventArgs)
    
      If FormsAuthentication.Authenticate(txtUser.Text, txtPassword.Text) Then
         FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)
      Else
         ErrorMessage.InnerHtml = "<b>Something went wrong...</b> please re-enter your credentials..."
      End If
    
    End Sub
    </script>
    <html>
    <head>
    <title>Standard Forms Authentication Login Form</title>
    </head>
    
    <body bgcolor="#FFFFFF" text="#000000">
    <form runat="server">
    <table width="400" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td width="80">Username : </td>
        <td width="10"> </td>
        <td><asp:TextBox Id="txtUser" width="150" runat="server"/></td>
      </tr>
      <tr>
        <td>Password : </td>
        <td width="10"> </td>
        <td><asp:TextBox Id="txtPassword" width="150" TextMode="Password" runat="server"/></td>
      </tr>
      <tr>
      <tr>
        <td></td>
        <td width="10"> </td>
        <td><asp:CheckBox id="chkPersistLogin" runat="server" />Remember my credentials<br>
        </td>
      </tr>
      <tr>
        <td> </td>
        <td width="10"> </td>
        <td><asp:Button Id="cmdLogin" OnClick="ProcessLogin" Text="Login" runat="server" /></td>
      </tr>
    </table>
    <br>
    <br>
    <div id="ErrorMessage" runat="server" />
    </form>
    </body>
    </html>
    
    

    Login.aspx Details

    I have referenced the System.Web.Security namespace since we will be working with authentication. All methods of authentication reside in this namespace. FormsAuthentication is a class of the System.Web.Security namespace. Here we have a simple server-side form setup with one textbox and one password input for username and password. I have included a check box in case the user wants to have a permanent cookie set. The Submit button has an event "onclick" which runs a sub called ProcessLogin. Inside ProcessLogin we execute the Authenticate method of the FormsAuthentication class, passing in the given username and password. This method checks the credential's tags inside the Web.config for the username and password. If they match, then we execute the RedirectFromLoginPage with the username and persistent cookie state (if checked). This method then writes a cookie to the user's machine to track them and ensure they are authenticated. If the username and password do not match, then an error occurs and the user is notified.

    Default.aspx Overview

    This is the page the user is requesting or trying to access. Here we will display the currently authenticated user and the authentication type.

    Default.aspx Code

    
    <%@Page Language="VB" %>
    <%@Import Namespace="System.Web.Security" %>
    <script language="vb" runat="server">
    Sub SignOut(objSender As Object, objArgs As EventArgs)
      'delete the users auth cookie and sign out
      FormsAuthentication.SignOut()
      'redirect the user to their referring page
      Response.Redirect(Request.UrlReferrer.ToString())
    End Sub
    Sub Page_Load()
      'verify authentication
      If User.Identity.IsAuthenticated Then
        'display Credential information
        displayCredentials.InnerHtml = "Current User : <b>" & User.Identity.Name & "</b>" & _
           "<br><br>Authentication Used : <b>" & User.Identity.AuthenticationType & "</b>"
      Else
        'Display Error Message
        displayCredentials.InnerHtml = "Sorry, you have not been authenticated."
      End If
    End Sub
    </script>
    <html>
    <head>
    	<title>Forms Authentication</title>
    </head>
    <body bgcolor="#FFFFFF" text="#000000">
    <span class="Header">Forms Based Authentication using standard method</span>
    <br>
    <br>
    <div id="displayCredentials" runat="server" />
    <br>
    <br>
    <form runat="server">
      <asp:Button id="cmdSignOut" text="Sign Out" runat="server" onClick="SignOut" />
    </form>
    </body>
    </html>
    
    

    Again I have referenced the System.Web.Security namespace since we will need some of its methods and properties. This page contains a simple div element thatwill display the current credentials and authentication type used. There is also a signout input element that runs a sub that deletes the user's cookie. They are then redirected to the login page. In the Page_Load event, I check to see if the user has been authenticated using the User.Identity.IsAuthenticated property. This returns a Boolean value indicating whether or not the user has been authenticated. If the user is authenticated, we want to display the current user's name and the authentication method used. We can access the currently logged on user's name with the User.Identity.Name property. User.Identity.AuthenticationType returns the mode of authentication used. We also use a SignOut procedure that allows the user to sign out and deletes the cookie from the user's computer. This will even delete a persistent cookie.

    Conclusion

    I hope that this has given you the basic understanding of Forms Authentication and how it can be useful for you. If you have any questions or comments about the concepts or code in this article, please feel free to contact me.

    Resources

    Forms Authentication in ASP.NET -- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhandlingformsauthenticationevents.asp

    Machine.config - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstep1examiningconfigurationfiles.asp

    DES - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/secglos_9661.asp

    About the Author

    Jeff Gonzalez has been working in the IT industry for the last six years. He started his IT career as an NT4 administrator and network engineer. While working for a hosting company, he recognized the power of Windows DNA and sought out to learn everything he could about it. Since his foray into the Internet development world, he has worked on several e-commerce, e-business, and intranet applications. Jeff is currently working at Microsoft doing ASP.NET, VS.NET, and mobility controls support. He can be reached at rjg444@hotmail.com.