ASP.NET Tutorial/Authentication Authorization/Form Based

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Automatically Redirecting a User to the Referring Page

   <source lang="csharp">

If you request the Login.aspx page directly, after you successfully log in, you are redirected to the Default.aspx page. If you add the Login control to a page other than the Login.aspx page, you need to set the Login control"s DestinationPageUrl property. When you successfully log in, you are redirected to the URL represented by this property. If you don"t supply a value for the DestinationPageUrl property, the same page is reloaded. Automatically Hiding the Login Control from Authenticated Users The easiest way to add a Login control to all the pages in an application is to take advantage of Master Pages. You can change the layout of the Login control by modifying the Login control"s Orientation property. If you set this property to the value Horizontal, then the Username and Password text boxes are rendered in the same row. If you include a Login control in all your pages, you should also modify the Login control"s VisibleWhenLoggedIn property. If you set this property to the value False, then the Login control is not displayed when a user has already authenticated. File: LoginMaster.master <%@ Master Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>My Website</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Login
       id="Login1"
       Orientation="Horizontal"
       VisibleWhenLoggedIn="false"
       DisplayRememberMe="false"
       TitleText=""
       CssClass="login"
       Runat="server" />

       <asp:contentplaceholder
           id="ContentPlaceHolder1"
           runat="server">
       </asp:contentplaceholder>
   </form>

</body> </html> File: LoginContent.aspx <%@ Page Language="C#" MasterPageFile="~/LoginMaster.master" %> <asp:Content

   ID="Content1"
   ContentPlaceHolderID="ContentPlaceHolder1"
   Runat="Server">

Welcome to our Website!

</asp:Content></source>


Create a new folder in your application named SecretFiles

   <source lang="csharp">

Add the page, File: SecretFiles\Secret.aspx <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Secret</title>

</head> <body>

   <form id="form1" runat="server">

This Page is Secret!

   </form>

</body> </html>

By default, Windows authentication is enabled. To use the Login controls, you need enable Forms authentication File: Web.Config <configuration>

 <system.web>
   <authentication mode="Forms" />
 </system.web>

</configuration>

By default, all users have access to all pages in an application. If you want to restrict access to the pages in a folder, then you need to configure authorization for the folder. Add the following web configuration file to the SecretFiles folder. Then anonymous users are prevented from accessing any pages in the folder. The single authorization rule here prevents anonymous users from accessing pages in the folder. The ? represents anonymous users. File: SecretFiles\Web.Config <configuration>

 <system.web>
   <authorization>
     <deny users="?"/>
   </authorization>
 </system.web>

</configuration>

If you attempt to request the Secret.aspx page, then you are redirected to a page named Login.aspx automatically. By default, this page must be located in the root of your application. The Login.aspx page contains a Login control. The Login control automatically generates a login form. File: Login.aspx <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Login</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Login
       id="Login1"
       CreateUserText="Register"
       CreateUserUrl="~/Register.aspx"
       Runat="server" />
   </form>

</body> </html>

Login control includes a CreateUserText and CreateUserUrl property. Adding these properties to the Login control causes the control to display a link to a page that enables a new user to register for your application. The Login control links to a page named Register.aspx. File: Register.aspx <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Register</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:CreateUserWizard
       id="CreateUserWizard1"
       ContinueDestinationPageUrl="~/SecretFiles/Secret.aspx"
       Runat="server" />
   </form>

</body> </html>

The Register.aspx page contains a CreateUserWizard control. This control automatically generates a user registration form. After you submit the form, a new user is created, and you are redirected back to the Secret.aspx page.</source>


Customizing the Login form

   <source lang="csharp">

<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <style type="text/css">
       .login
       {
           width:250px;
           font:14px Verdana,Sans-Serif;
           background-color:lightblue;
           border:solid 3px black;
           padding:4px;
       }
       .login_title
       {
           background-color:darkblue;
           color:white;
           font-weight:bold;
       }
       .login_instructions
       {
           font-size:12px;
           text-align:left;
           padding:10px;
       }
       .login_button
       {
           border:solid 1px black;
           padding:3px;
       }
   </style>
   <title>Show Login</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Login
       id="Login1"
       InstructionText="Please log in before
           accessing the premium section of our Website."
       TitleText="Log In"
       TextLayout="TextOnTop"
       LoginButtonText="Log In"
       DisplayRememberMe="false"
       CssClass="login"
       TitleTextStyle-CssClass="login_title"
       InstructionTextStyle-CssClass="login_instructions"
       LoginButtonStyle-CssClass="login_button"
       Runat="server" />
   </form>

</body> </html></source>


Form authentication with backend database

   <source lang="csharp">

<%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <script language="VB" runat="server">

  sub Login(Sender as Object, e as EventArgs) 
     dim intID as integer = 0
     dim Conn as new OleDbConnection("Provider=" & _
           "Microsoft.Jet.OLEDB.4.0;" & _
           "Data Source=userTable.mdb")
     dim objCmd as OleDbCommand = new OleDbCommand _
        ("SELECT UserID FROM tblUsers WHERE " & _
        "Username = "" & tbUserName.Text & "" " & _
        "AND Password = "" & tbPassword.Text & """, Conn)
     dim objReader as OleDbDataReader
     try
        objCmd.Connection.Open()
        objReader = objCmd.ExecuteReader()
        do while objReader.Read
           intId = objReader.GetInt32(0).ToString()
        loop
     catch ex as OleDbException
        lblMessage.Text = ex.Message
     finally
        objReader.Close()
        objCmd.Connection.Close()
     end try
     if intID <> 0 then
        FormsAuthentication.SetAuthCookie(intID, false)
        lblMessage.Text = "Success!"
     else
        lblMessage.Text = "Invalid username or password!"
     end if
  end sub      

</script> <html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server"/>
     Username:
     <asp:Textbox id="tbUsername" runat="server" />
Password: <asp:Textbox id="tbPassword" TextMode="password" runat="server" /> <asp:Button id="Submit" runat="server" onClick="Login" text="Submit" /> </form>

</body></html>

File: Web.Config <configuration>

  <system.web>
     <authentication mode="Forms">
        <forms name="AuthCookie" loginUrl="login.aspx" />
     </authentication>
     <authorization> 
        <deny users="?"/> 
     </authorization> 
  </system.web>

</configuration></source>