ASP.NET Tutorial/Authentication Authorization/Membership

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

After a user has been locked out, you must call the MembershipUser.UnlockUser() method to re-enable the user account.

   <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"> <script runat="server">

   protected void btnRemove_Click(object sender, EventArgs e)
   {
       MembershipUser userToUnlock = Membership.GetUser(txtUserName.Text);
       if (userToUnlock == null)
       {
           lblMessage.Text = "User not found!";
       }
       else
       {
           userToUnlock.UnlockUser();
           lblMessage.Text = "Lock removed!";
       }
   }

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

   <title>Remove Lock</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblUserName"
       Text="User Name:"
       AssociatedControlID="txtUserName"
       Runat="server" />
   <asp:TextBox
       id="txtUserName"
       Runat="server" />
   <asp:Button
       id="btnRemove"
       Text="Remove Lock"
       Runat="server" OnClick="btnRemove_Click" />
   
<asp:Label id="lblMessage" EnableViewState="false" Runat="server" />
   </form>

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


Configure how passwords are stored by setting the passwordFormat attribute in the web configuration file.

   <source lang="csharp">

The following web configuration file configures the SqlMembershipProvider to store passwords in plain text. File: Web.Config <configuration>

   <system.web>
     <authentication mode="Forms" />
     <membership defaultProvider="MyProvider">
       <providers>
         <add
           name="MyProvider"
           type="System.Web.Security.SqlMembershipProvider"
           passwordFormat="Clear"
           connectionStringName="LocalSqlServer"/>
       </providers>
     </membership>
   </system.web>

</configuration></source>


Creating users programmatically (C#)

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server">

   protected void Button1_Click(object sender, EventArgs e)
   {
       try
       {
           Membership.CreateUser(TextBox1.Text.ToString(), TextBox2.Text.ToString());
           Label1.Text = "Successfully created user " + TextBox1.Text;
       }
       catch (MembershipCreateUserException ex)
       {
           Label1.Text = "Error: " + ex.ToString();
       }
   }

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

   <title>Creating a User</title>

</head> <body>

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

Create User

       Username
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox> Password
<asp:TextBox ID="TextBox2" Runat="server" TextMode="Password"></asp:TextBox> <asp:Button ID="Button1" Runat="server" Text="Create User" OnClick="Button1_Click" /> <asp:Label ID="Label1" Runat="server"></asp:Label> </form>

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


Creating users programmatically (VB)

   <source lang="csharp">

<%@ Page Language="VB" %> <script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

  Try
     Membership.CreateUser(TextBox1.Text, TextBox2.Text)
     Label1.Text = "Successfully created user " & TextBox1.Text
  Catch ex As MembershipCreateUserException
     Label1.Text = "Error: " & ex.ToString()
  End Try

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

   <title>Creating a User</title>

</head> <body>

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

Create User

       Username
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox> Password
<asp:TextBox ID="TextBox2" Runat="server" TextMode="Password"></asp:TextBox> <asp:Button ID="Button1" Runat="server" Text="Create User" OnClick="Button1_Click" /> <asp:Label ID="Label1" Runat="server"></asp:Label> </form>

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


Denying unauthenticated users

   <source lang="csharp">

<?xml version="1.0" encoding="utf-8"?> <configuration>

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

</configuration></source>


Disable this requirement when using the SqlMembershipProvider.

   <source lang="csharp">

<configuration>

 <system.web>
   <authentication mode="Forms" />
   <membership defaultProvider="MyProvider">
     <providers>
       <add
         name="MyProvider"
         type="System.Web.Security.SqlMembershipProvider"
         minRequiredNonalphanumericCharacters="0"
         connectionStringName="LocalSqlServer"/>
     </providers>
   </membership>
 </system.web>

</configuration></source>


Locking Out Bad Users

   <source lang="csharp">

Two configuration settings control when an account gets locked out: maxInvalidPasswordAttempts, passwordAttemptWindow Enter a maximum of three bad passwords or bad password answers in one hour. File: Web.Config <configuration>

 <system.web>
   <authentication mode="Forms" />
   <membership defaultProvider="MyProvider">
     <providers>
       <add
         name="MyProvider"
         type="System.Web.Security.SqlMembershipProvider"
         maxInvalidPasswordAttempts="3"
         passwordAttemptWindow="60"
         connectionStringName="LocalSqlServer"/>
     </providers>
   </membership>
 </system.web>

</configuration></source>


Membership provider settings in the machine.config file

   <source lang="csharp">

<membership>

  <providers>
     <add name="AspNetSqlMembershipProvider"
      type="System.Web.Security.SqlMembershipProvider, System.Web,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
      connectionStringName="LocalSqlServer"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="true"
      applicationName="/"
      requiresUniqueEmail="false"
      passwordFormat="Hashed"
      maxInvalidPasswordAttempts="5"
      passwordAttemptWindow="10"
      passwordStrengthRegularExpression="" />
  </providers>

</membership></source>


Setting Up Your Web Site for Membership

   <source lang="csharp">

Adding an <authentication> Element to the web.config File

<?xml version="1.0" encoding="utf-8"?> <configuration>

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

</configuration>

Adding a <forms> Element to the web.config File

<?xml version="1.0" encoding="utf-8"?> <configuration>

   <system.web>
       <authentication mode="Forms">
          <forms name=".ASPXAUTH"
                 loginUrl="login.aspx"
                 protection="All"
                 timeout="30"
                 path="/"
                 requireSSL="false"
                 slidingExpiration="true"
                 cookieless="useDeviceProfile" />
       </authentication>
   </system.web>

</configuration>

name: the name used for the cookie loginUrl: page location to which the HTTP request is redirected for login protection: protection applied to the cookie.

                  The possible settings include All, None, Encryption, and Validation. 

timeout: amount of time (in minutes) after which the cookie expires.

                  The default value is 30 minutes.

path: Specifies the path for cookies issued by the application. requireSSL: whether you require that credentials be sent over an encrypted wire (SSL) instead of clear text. slidingExpiration: whether the timeout of the cookie is on a sliding scale. cookieless: how the cookies are handled by ASP.NET.

                  The possible values include useDeviceProfile, useCookies, auto, and useUri. 
                  The default value is useDeviceProfile. 
                  

Using the CreateUserWizard Server Control

<%@ Page Language="VB" %>

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

   <title>Creating Users</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:CreateUserWizard ID="CreateUserWizard1" Runat="server"
        BorderWidth="1px" BorderColor="#FFDFAD" BorderStyle="Solid"
        BackColor="#FFFBD6" Font-Names="Verdana">
           <TitleTextStyle Font-Bold="True" BackColor="#990000"
            ForeColor="White"></TitleTextStyle>
       </asp:CreateUserWizard>
   </form>

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


The web configuration file used to set up the XmlMembershipProvider

   <source lang="csharp">

File: Web.Config <configuration>

   <system.web>
     <authentication mode="Forms" />
     <membership defaultProvider="MyMembershipProvider">
       <providers>
         <add
           name="MyMembershipProvider"
           type="MyNamespace.XmlMembershipProvider"
           dataFile="~/App_Data/Membership.xml"
           requiresQuestionAndAnswer="false"
           enablePasswordRetrieval="true"
           enablePasswordReset="true"
           passwordFormat="Clear" />
       </providers>
     </membership>
   </system.web>

</configuration>

A sample of the Membership.xml file. File: App_Data\Membership.xml <credentials>

 <user name="Tom" password="secret" email="tom@somewhere.ru" />
 <user name="Jack" password="secret" email="jack@somewhere.ru" />

</credentials></source>


Use the methods of the Membership class to create custom Login controls.

   <source lang="csharp">

using System; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; namespace myControls {

   public class UsersOnline : WebControl
   {
       protected override void RenderContents(HtmlTextWriter writer)
       {
           writer.Write(Membership.GetNumberOfUsersOnline());
       }
   }

}

File: ShowUsersOnline.aspx <%@ Page Language="C#" %> <%@ Register TagPrefix="custom" Namespace="myControls" %> <!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>Show UsersOnline</title>

</head> <body>

   <form id="form1" runat="server">
   How many people are online?
   
<custom:UsersOnline id="UsersOnline1" Runat="server" />
   </form>

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


Using ASP.NET Membership

   <source lang="csharp">

ASP.NET Membership uses the provider model. The ASP.NET Framework includes two Membership providers: SqlMembershipProvider stores user information in a Microsoft SQL Server database. ActiveDirectoryMembershipProvider stores user information in the Active Directory or an Active Directory Application Mode server.</source>


Using the Membership Application Programming Interface

   <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">

   <title>List Users</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:GridView
       id="grdUsers"
       DataSourceID="srcUsers"
       Runat="server" />
   <asp:ObjectDataSource
       id="srcUsers"
       TypeName="System.Web.Security.Membership"
       SelectMethod="GetAllUsers"
       Runat="server" />
   </form>

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