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.

<%@ 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">
    <div>
    <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" />
    <br />
    <asp:Label
        id="lblMessage"
        EnableViewState="false"
        Runat="server" />
    </div>
    </form>
</body>
</html>


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

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>


Creating users programmatically (C#)

<%@ 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">
        <h1>Create User</h1>
        Username<br />
            <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        
        Password<br />
            <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>


Creating users programmatically (VB)

<%@ 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">
        <h1>Create User</h1>
        Username<br />
            <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        
        Password<br />
            <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>


Denying unauthenticated users

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authentication mode="Forms" />
        <authorization>
           <deny users="?" />
        </authorization>
    </system.web>
</configuration>


Disable this requirement when using the SqlMembershipProvider.

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


Locking Out Bad Users

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>


Membership provider settings in the machine.config file

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


Setting Up Your Web Site for Membership

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>


The web configuration file used to set up the XmlMembershipProvider

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>


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

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">
    <div>
    How many people are online?
    <br/>
    <custom:UsersOnline
        id="UsersOnline1"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Using ASP.NET Membership

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.


Using the Membership Application Programming Interface

<%@ 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">
    <div>
    <asp:GridView
        id="grdUsers"
        DataSourceID="srcUsers"
        Runat="server" />
    <asp:ObjectDataSource
        id="srcUsers"
        TypeName="System.Web.Security.Membership"
        SelectMethod="GetAllUsers"
        Runat="server" />
    </div>
    </form>
</body>
</html>