Microsoft ASP Net 3.5 Step By Step (phần 9) docx

30 326 0
Microsoft ASP Net 3.5 Step By Step (phần 9) docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 10 Logging In 211 The CD that comes with this book includes this login page. To see an example of the most basic authentication you can use in your application, take a look at the fi les Login.aspx and Web.Confi gFormsAuthentication. The web.confi g fi le includes the Authentication and Authorization elements to support Forms Authentication for the site. Listing 10-1 shows the web.confi g settings necessary to force authentication. LISTING 10-1 A Basic Web.Confi g File Requiring Authentication <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="login.aspx" /> </authentication> <authorization> <deny users="?" /> </authorization> </system.web> </configuration> The login page that goes with it is shown in Listing 10-2. LISTING 10-2 A Basic ASP.NET Login Page <%@ Page language=C# %> <html> <script runat=server> protected bool AuthenticateUser(String strUserName, String strPassword) { if (strUserName == "Gary") { if(strPassword== "K4T-YYY") { return true; } } else if(strUserName == "Jay") { if(strPassword== "RTY!333") { return true; } } else if(strUserName == "Susan") { if(strPassword== "erw3#54d") { return true; } } return false; } public void OnLogin(Object src, EventArgs e) { if (AuthenticateUser(m_textboxUserName.Text, m_textboxPassword.Text)) { <con f i g uration > <s y stem.web> <a uthe n tic a tio n m ode = " F o rm s"> <forms loginUrl="login.aspx" / > < / aut h ent i cat i on > <aut h or i zat i on > <deny users="?" / > </authorization > </s y stem.web > </confi g uration > <%@ Page l anguage=C# %> < h tm l> <script runat=server> protected bool AuthenticateUser(Strin g strUserName , Strin g strPassword) { if (strUserName == "Gar y ") { if(strPassword== "K4T-YYY") { re t urn t rue ; } } else i f (strUserName == "Jay") { i f (strPassword== "RTY!333") { return true ; } } else if(strUserName == "Susan") { if ( strPassword== "erw3#54d" ) { re t urn t rue ; } } return f alse ; } pu bli c vo id OnLog i n ( O bj ect src, EventArgs e ) { if (AuthenticateUser(m_textboxUserName.Text , m_text b oxPasswor d .Text )) { 212 Part II Advanced Features FormsAuthentication.RedirectFromLoginPage( m_textboxUserName.Text, m_bPersistCookie.Checked); } else { Response.Write("Invalid login: You don’t belong here "); } } </script> <body> <form runat=server> <h2>A most basic login page</h2> User name: <asp:TextBox id="m_textboxUserName" runat=server/><br> Password: <asp:TextBox id="m_textboxPassword" TextMode="password" runat=server/> <br/> Remember password and weaken security?: <asp:CheckBox id=m_bPersistCookie runat="server"/> <br/> <asp:Button text="Login" OnClick="OnLogin" runat=server/> <br/> </form> </body> </html> This is a simple login page that keeps track of three users—Gary, Jay, and Susan. In this scenario, even if users try to surf to any page in the virtual directory, ASP.NET will stop them dead in their tracks and force them to pass the login page shown in Figure 10-3. FIGURE 10-3 A simple login page for getting a user name and password from a client FormsAuthentication.RedirectFromLo g inPa g e ( m_textboxUserName.Text , m_bPersistCookie.Checked) ; } else { Response.Write("Invalid lo g in: You don’t belon g here ") ; } } < / scr ip t > < b o d y > < f orm runat=server> <h2>A most basic lo g in pa g e</h2 > U ser name: <as p :TextBox id="m_textboxUserName" runat=server/><br > Pa ss w o r d: <as p :TextBox id = " m_text b oxPasswor d" TextMo d e= "p asswor d" runat=server /> < b r /> Remem b er passwor d an d wea k en secur i ty? : <asp:CheckBox id=m_bPersistCookie runat="server"/ > <br/ > <asp:Button text="Lo g in" OnClick="OnLo g in " runat=server/ > <br/ > < / form > < /b o dy > < /h tm l> Chapter 10 Logging In 213 This simple login page authenticates the user (out of a group of three possible users). In a real Web site, the authentication algorithm would probably use a database lookup to see if the user identifying himself or herself is in the database and whether the password matches. Later in this chapter, we’ll see the ASP.NET authentication services. The login page then issues an authentication cookie using the FormsAuthentication utility class. Figure 10-4 shows what the Web page looks like in the browser with tracing turned on. Here you can see the value of the authentication cookie in the (request) cookies collection. FIGURE 10-4 Tracing turned on reveals the authentication cookie for a page using Forms Authentication. Run the Forms Authentication example This example shows how to employ Forms Authentication on your site. 1. To run the Forms Authentication example, create a virtual directory to hold the site. Add an HTML fi le to the directory that simply displays a banner text “Hello World.” Name the fi le Default.htm. You need to have a target fi le to surf to for Forms Authentication to work. Alternatively, you can use an already existing site and employ Forms Authentication there. 2. Copy the Login.aspx page from the Chapter 10 examples on the CD with this book into the virtual directory for which you want to apply Forms Authentication. 214 Part II Advanced Features 3. Copy the Web.Confi gForceAuthentication fi le from the Chapter 10 examples on the CD with this book into the virtual directory for which you want to apply Forms Authentication. Make sure to rename the confi guration fi le web.confi g after you copy it. 4. Try to surf to a page in that virtual directory. ASP.NET should force you to complete the Login.aspx page before moving on. 5. Type in a valid user name and password. Subsequent access to that virtual directory should work just fi ne because now there’s an Authentication ticket associated with the request and response. Although you may build your own authentication algorithms, ASP.NET includes a number of new features that make authenticating users a straightforward and standard proposition. We’ll look at those in a moment. Briefl y, ASP.NET allows two other types of authentication: Passport authentication and Windows authentication. There’s not much talk about Passport anymore. Passport authenti- cation has evolved into the Windows Live ID and requires a centralized authentication service provided by Microsoft. If you’ve ever used Hotmail.com, you’ve used Windows Live ID. The advantage of Windows Live ID authentication is that it centralizes login and personalization information at one source. While this is not a free service, your users can use a single user ID to log into many Web sites, providing convenience and easing your own development needs as you don’t need to manage user authentication yourself. The other type of authentication supported by ASP.NET is Windows authentication. If you specify Windows authentication, ASP.NET relies on IIS and Windows authentication to man- age users. Any user making his or her way through IIS authentication (using basic, digest, or Integrated Windows Authentication as confi gured in IIS) will be authenticated for the Web site. These other forms of authentication are available when confi guring IIS. However, for most ASP.NET Web sites, you’ll be bypassing IIS authentication in favor of ASP.NET authenti- cation even if only for scalability reasons. ASP.NET will use the authenticated identity to man- age authorization. ASP.NET Authentication Services ASP.NET includes a great deal of support for authenticating users (outside of IIS’s support). Most of it comes from the FormsAuthentication class. The FormsAuthentication Class Many of ASP.NET’s authentication services center around the FormsAuthentication class. The examples shown in Listings 10-1 and 10-2 show how the rudimentary authentication works Chapter 10 Logging In 215 by installing an authentication cookie in the response and redirecting the processing back to the originally requested page. This is the primary purpose of FormsAuthentication .RedirectFromLoginPage. There are some other interesting methods in the FormsAuthentication class that allow for fi ner-grained control over the authentication process. For example, you can authenticate users manually (without forcing a redirect). That’s useful for creating optional login pages that vary their content based on the authentication level of the client. FormsAuthentication includes a number of other services as well. Table 10-1 shows some of the useful members of the FormsAuthentication class. TABLE 10-1 Useful FormsAuthentication Class Members FormsAuthentication Method Description CookiesSupported Property indicating whether cookies are supported for authentication FormsCookieName Property representing the forms authentication cookie name FormsCookiePath Property representing the forms authentication cookie path LoginUrl Redirects URL for logging in RequireSSL Property representing whether secure sockets layer is required SlidingExpiration Property indicating whether sliding expiration is set Authenticate Authenticates the user Encrypt Generates an encrypted string representing a forms- authentication ticket suitable for use in an HTTP cookie Decrypt Creates a FormsAuthenticationTicket from an encrypted forms-authentication ticket GetAuthCookie Creates an authentication cookie for a specifi c user GetRedirectUrl Gets the original URL to which the client was surfi ng HashPasswordForStoringInConfi gFile Creates a hashed password suitable for storing in a credential store RedirectFromLoginPage Authenticates the user and redirects to the originally requested page SignOut Invalidates the authentication ticket An Optional Login Page The code accompanying this book also includes an example showing how to authenticate separately. The page in Listing 10-3 uses the same authentication algorithm (three users— Gary, Jay, and Susan—with hard-coded passwords). However, the page authenticates users and then redirects them back to the same page (OptionalLogin.aspx). F ormsAuthenticatio n Metho d Descr i pt i on 216 Part II Advanced Features LISTING 10-3 OptionalLogin.aspx <%@ Page language=C# trace="false"%> <html> <script runat=server> protected bool AuthenticateUser(String strUserName, String strPassword) { if (strUserName == "Gary") { if(strPassword== "K4T-YYY") { return true; } } else if(strUserName == "Jay") { if(strPassword== "RTY!333") { return true; } } else if(strUserName == "Susan") { if(strPassword== "erw3#54d") { return true; } } return false; } public void OnLogin(Object src, EventArgs e) { if (AuthenticateUser(m_textboxUserName.Text, m_textboxPassword.Text)) { FormsAuthentication.SetAuthCookie( m_textboxUserName.Text, m_bPersistCookie.Checked); Response.Redirect("optionallogin.aspx"); } else { Response.Write("Invalid login: You don’t belong here "); } } protected void ShowContent() { if(Request.IsAuthenticated) { Response.Write("Hi, you are authenticated. <br>" ); Response.Write("You get special content <br>" ); } else <%@ Page language=C# trace="false"% > < h tm l> <scr i pt runat=server> protected bool AuthenticateUser(Strin g strUserName , Strin g strPassword ) { i f (strUserName == "Gar y " ) { if ( strPassword== "K4T-YYY" ) { re t urn t rue ; } } else i f (strUserName == "Jay" ) { i f (strPassword== "RTY!333" ) { re t urn t rue ; } } else i f( strUserName == "Susan" ) { i f (strPassword== "erw3#54d" ) { return true ; } } return false; } pu bli c vo id OnLo gi n ( O bj ect src, EventAr g s e ) { i f (AuthenticateUser(m_textboxUserName.Text , m_textboxPassword.Text) ) { FormsAuthentication.SetAuthCookie ( m_text b oxUserName.Text , m_ b Pers i stCoo ki e.C h ec k e d); Response.Re di rect (" opt i ona ll og i n.aspx "); } e l se { Response.Wr i te (" Inva lid l o gi n: You d on ’ t b e l on g h ere "); } } p rotected void ShowContent( ) { if(Re q uest.IsAuthenticated ) { Response.Wr i te (" H i , you are aut h ent i cate d . < b r> " ); Response.Write("You g et special content <br>" ) ; } else Chapter 10 Logging In 217 { Response.Write("You're anonymous. Nothing special for you "); } } </script> <body><form runat=server> <h2>Optional Login Page</h2> User name: <asp:TextBox id="m_textboxUserName" runat=server/><br> Password: <asp:TextBox id="m_textboxPassword" TextMode="password" runat=server/> <br/> Remember password and weaken security?: <asp:CheckBox id=m_bPersistCookie runat="server"/> <br/> <asp:Button text="Login" OnClick="OnLogin" runat=server/> <br/> <%ShowContent(); %> </form></body> </html> Notice that the page sets the authentication cookie manually by calling FormsAuthentication .SetAuthCookie and then redirects the processing back to the page. Each time the page shows, it calls the ShowContent method, which checks the authentication property in the page to decide whether or not to display content specialized for an authenticated user. Because the page redirects manually after authenticating, the web.confi g fi le needs to look a bit different. To make it work, the authentication node should remain, but the authorization node that denies anonymous users needs to be removed. That way, any user can log in to the OptionLogin.aspx page (they won’t be denied) but they may proceed after they’re authen- ticated. Here’s the new web.confi g fi le, shown in Listing 10-4. The fi le on the CD is named Web.Confi gForOptionalLogin. To make it apply to the application, copy the fi le and name it as web.confi g. LISTING 10-4 A Web.Confi g File Supporting Optional Login <configuration> <system.web> <authentication mode="Forms"> </authentication> </system.web> </configuration> { Response.Write("You're anonymous. Nothin g special f or you ") ; } } </scri p t > <bod y ><form runat=server > < h 2>Opt i ona l Log i n Page< /h 2 > User name: <asp:TextBox id="m_textboxUserName" runat=server/><br > Pa ss w o r d: <asp:TextBox id="m_textboxPassword " TextMode=" p assword" runat=server/ > <br/ > Remem b er p asswor d an d wea k en secur i t y ? : <as p :C h ec k Box id =m_ b Pers i stCoo ki e runat= " server "/> < b r /> <asp:Button text= " Log i n " OnC li c k = " OnLog i n " runat=server /> <br/ > <%ShowContent() ; % > </form></bod y > < /h tm l> 218 Part II Advanced Features Figure 10-5 shows how the optional login page appears before the user has been authenticated. FIGURE 10-5 The optional login page before an authenticated user logs in. Run the optional login page This example shows how to run the optional login page. 1. To run the optional login page, create a virtual directory to hold the site. Alternatively, you can use an already existing site and try the optional login page from there. 2. Copy the OptionalLogin.aspx page from the Chapter 10 examples on the CD with this book into the virtual directory. 3. Copy the Web.Confi gOptionalLogin from the Chapter 10 examples on the CD with this book into the virtual directory. Be sure to rename the confi guration fi le web.confi g so ASP.NET loads the appropriate confi guration settings. 4. Try to surf to a page in that virtual directory. ASP.NET should allow you to see the page, but as an unauthenticated user. Chapter 10 Logging In 219 5. Type in a valid user name and password. You should see the content tailored for au- thenticated users. Subsequent requests/responses to and from the site will include an authentication token, so you would always see the special authenticated content. After the user has been authenticated, the optional login page shows the content tailored to the specifi c authenticated user. Figure 10-6 shows the page after an authenticated user logs in. FIGURE 10-6 An authenticated user has logged in Managing Users So far, you can see that the fundamentals behind employing Forms Authentication are easy to manage. In the previous examples, the pages are inaccessible until you prove your identity. The example above shows raw authentication with the users and passwords hard-coded into the ASPX fi le. This is useful for illustration. However, in a production application you’ll un- doubtedly want to assign identities to the authorized users visiting your site. ASP.NET and Visual Studio include facilities for both managing user identities and managing roles. The following exercise shows how to set up a secure site in which users are allowed access only after they identify themselves correctly. 220 Part II Advanced Features Managing user access 1. Create a new Web site named SecureSite. 2. Add a label to the Default.aspx page with the text “Congratulations. You made it in.” That way, when you get to the default page after logging in, you’ll know which page it is in the browser. 3. Open the ASP.NET Web Site Administration Tool by selecting Web Site, ASP.NET Confi guration from the main menu. Go to the Provider tab. Select the Select A Single Provider For All Site Management Data link. You can click the Test link to test the provider to make sure the connection is working. Tip As you recall from Chapter 9, IIS includes ASP.NET confi guration facilities as well. If your site has a virtual directory, you can get to the facilities by opening IIS, selecting the virtual directory of interest, and navigating among the Features icons. 4. Run the program aspnet_regsql.exe to create a a data store to hold membership informa- tion. You’ll fi nd aspnet_regsql.exe in C:\Windows\Microsoft.NET\Framework\v2.0.50727>. 5. Go to the Security tab. You’ll see the page shown in the following graphic. Click the Select Authentication Type link. [...]... instruction to ASP. NET about what to do There’s no login redirect and no login page yet, so ASP. NET simply stops you in your tracks Let’s provide a login page using the ASP. NET login controls ASP. NET Login Controls Earlier in this chapter, we handcrafted a couple of different login pages During the heyday of ASP. NET 1.1, that’s what you had to do to get Forms Authentication working Modern ASP. NET improves... your application 1 Use the ASP. NET Web Site Administration tool (select Web Site, ASP. NET Configuration) 2 Use the ASP. NET tab in IIS Configure the security aspects of your Web site 1 Use the ASP. NET Web Site Administration Tool (select Web Site, ASP. NET Configuration) 2 Use the ASP. NET tab in IIS Authenticate a request by hand Use the FormsAuthentication class’s Set Auth cookie Invalidate an authentication... like so: 2 By selecting Internet access through the ASP. NET Web Site Administration Tool, ASP. NET understands to use Forms Authentication The default login URL is Login.aspx 228 Part II Advanced Features Now try to surf to the default page ASP. NET will confront you with the login page, like so: You’ll see the default page (provided you logged in successfully): Authentication is an important step in managing... you decide to let ASP. NET handle authentication, then you have more control over how the authentication happens while at the same time leaving your set of Windows user identities unadulterated To let a request get past IIS, allow anonymous access to your virtual directory Once a request gets past IIS, it’s up to ASP. NET to figure out who the user is and how to dole out access ASP. NET includes an authentication... element by hand) or use the Web Site Administration Tool (or the IIS ASP. NET tab) to turn on Forms Authentication The Web Site Administration Tool is useful for adding users, adding roles, and assigning users to roles It’s the most convenient way to manage users and roles (If you want to, you may set up your own authentication scheme and database, bypassing the ASP. NET support, but this... this book.) By using ASP. NET authentication and authorization support, the login controls work automatically The login controls supply login functionality for the majority of use cases (As always, you may bypass the support for an authentication and authorization scheme of your own choosing.) Chapter 10 Quick Reference To Do This Use Forms Authentication in your application 1 Use the ASP. NET Web Site... Chapter 10 Logging In 225 10 Now try running the site ASP. NET should deny you access to the site, as shown here: ASP. NET is looking for a way to authenticate the user However, the site doesn’t have one yet The Forms... After completing this chapter, you will be able to Represent collections using data-bound controls Talk to database providers in ASP. NET Customize data-bound controls This chapter covers one of ASP. NET s most useful features: data binding A number of controls within ASP. NET have the capability to understand the form and content of a collection and to render the correct tags to represent such user elements... password security by saving their passwords on the machine The control exposes properties through which you can change the text and appearance of the control You may also add links to manage registration or password recovery The Login control interacts with the ASP. NET membership component for authentication by default If you want to manage authentication yourself, you may do so by handling the control’s... depending on the membership provider used by your application Chapter 10 Logging In 227 The following exercise illustrates how to write a login page using the login controls Write a login page 1 Create a Login page ASP. NET wants to see a login page for the SecureSite application called Login.aspx Add a regular Web form to your application Name the form Login.aspx Grab a Login control from the toolbox . Run the program aspnet_regsql.exe to create a a data store to hold membership informa- tion. You’ll fi nd aspnet_regsql.exe in C:Windows Microsoft. NET Frameworkv2.0 .50 727>. 5. Go to the Security. to ASP. NET about what to do. There’s no login redirect and no login page yet, so ASP. NET simply stops you in your tracks. Let’s provide a login page using the ASP. NET login controls. ASP. NET. guring IIS. However, for most ASP. NET Web sites, you’ll be bypassing IIS authentication in favor of ASP. NET authenti- cation even if only for scalability reasons. ASP. NET will use the authenticated

Ngày đăng: 07/07/2014, 06:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan