轉載:ASP.NET 2.0中使用Membership

  http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000022.asp

摘要:

本文介紹了怎麼在 ASP.NET 2.0 中使用 Membership 新特性,並且介紹了怎麼兩種不同的 Membership Provider ActiveDirectoryMembershipProvider SqlMembershipProvider ,前者是基於微軟活動目錄服務存儲用戶信息的,或者是基於 SQL SERVER 存儲的。 2.0 中的這個新機制大大減少了站點用戶認證模塊的代碼量。

目錄:

學習目的

使用 ActiveDirectoryMembershipProvider

使用 SqlMembershipProvider

ActiveDirectoryMembershipProvider 的一些設置參數

SqlMembershipProvider 的一些設置參數

Membership 的一些 API

學習目的:

學會使用 Membership 進行表單認證

學會設置 ActiveDirectoryMembershipProvider

學會使用 ActiveDirectoryMembershipProvider 建立認證用戶

學會設置 SqlMembershipProvider

學會建立 SQL SERVER Membership 數據庫

學會使用 SqlMembershipProvider 建立認證用戶

使用 ActiveDirectoryMembershipProvider

如果用戶信息是存儲在活動目錄中,而你的內網程序又因爲防火牆或者需要適應不同的瀏覽器等原因不能使用 windows 集成認證的話,這個時候你可以選擇使用 ActiveDirectoryMembershipProvider 實現表單認證

基本的步驟如下

按照以下步驟來用 ActiveDirectoryMembershipProvider 實現 asp.net 程序的用戶表單認證

1 、配置表單認證

2 、配置 ActiveDirectoryMembershipProvider

3 、建立用戶

4 、認證用戶

1 、配置表單認證

要實現表單認證需要設置 <authentication > mode 屬性爲 "Forms" ,然後按照下面的例子配置 web.config 文件

<authentication mode="Forms">

    <forms loginUrl="Login.aspx"

           protection="All"

           timeout="30"

            name="AppNameCookie"

           path="/FormsAuth"

           requireSSL="false"

           slidingExpiration="true"

           defaultUrl="default.aspx"

           cookieless="UseCookies"

           enableCrossAppRedirects="false"/>

</authentication>

 

·                     loginUrl 指向登錄頁面,你需要把它放在支持 SSL 的目錄下

·                     Protection 設置成 "All" 表示爲認證憑據同時啓用數據來源驗證和加密

·                     Timeout 指定了認證的生存時間

·                     name and path are set to unique values for the current application.

·                     requireSSL 設置成 "false" 表示關閉 cookie SSL 加密

·                     slidingExpiration 如果設置成 "true" 的話,每次訪問過期時間將會重置

·                     defaultUrl 就是設置程序的首頁

·                     cookieless 設置成 "UseCookies" 表示使用 cookie 來傳遞認證票據

·                     enableCrossAppRedirects 設置成 "false" 表示程序不接受外部的請求

按照下面的例子爲 <authentication > 增加 <authorization > 塊,表明只有登錄過的用戶才能進入程序否則會被轉到前面 loginUrl 設置的頁面

<authorization>

   <deny users="?" />

   <allow users="*" />

</authorization>

 

2 、配置 ActiveDirectoryMembershipProvider

按照下面的例子配置 ActiveDirectoryMembershipProvider

<connectionStrings>

  <add name="ADConnectionString"

   connectionString=

    "LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com" />

</connectionStrings>

 

<system.web>

  ...

  <membership defaultProvider="MembershipADProvider">

  <providers>

    <add

      name="MembershipADProvider"

      type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web,

            Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

                connectionStringName="ADConnectionString"

                connectionUsername="<domainName>/administrator"

                connectionPassword="password"/>

   </providers>

  </membership>

  ...

</system.web>

 

前面的代碼爲 <providers > 添加 <add > 子節點來爲 membership 指定 ActiveDirectoryMembershipProvider ,活動目錄中存儲用戶信息的連接字符串如下格式 LDAP:// server /userdn

·                     server 是活動目錄服務器的 IP 或者名字

·                     userdn 是活動目錄的 DN ,格式是 /CN=Users 然後是逗號加上逗號分割開的域名,比如域名是 domain.testing.com ,連接字符串就是 LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com

 

注意:確保 <membership > defaultProvider 屬性設置成了你的 ActiveDirectoryMembershipProvider (在這個例子中是 MembershipADProvider ),如果需要爲機器級別改變這個屬性, %windir%/Microsoft.NET/Framework/{Version}/Config/machine.config 文件中改寫原有的 AspNetSqlMembershipProvider AspNetSqlMembershipProvider 是使用 SQLMembershipProvider /app_data 目錄中的 SQL Server Express 數據庫來存放用戶信息的機制

3 、建立用戶

可以使用下面的幾種方法新建用戶

·                     打開 vs.net2005 Website 菜單,點擊 ASP.NET Configuration ,然後在安全裏面進行設置

·                     建立一個 ASP.NET 頁面,放入一個 CreateUserWizard 控件,這個控件使用配置過的 membership provider 來實現建立用戶的過程

·                     手動拖放填寫用戶名和密碼的文本框然後使用 Membership API CreateUser 方法來實現

 

注意:其實所有這些方法最終還是使用 Membership.CreateUser 來建立用戶

默認配置的 ActiveDirectoryMembershipProvider 使用 UPNs 來進行名字印象,如下

attributeMapUsername="userPrincipalName"

因爲所有用戶名都需要按照下面的格式:

UserName@DomainName

如果手動使用 Membership.CreateUser 方法來創建用戶,這麼做

Membership.CreateUser("UserName@DomainName", "P@ssw0rd", "userName@emailAddress");

 

你也能設置 config 文件來改變映象方式:

attributeMapUsername="sAMAccountName"

如果這樣設置的話,用戶名就如下格式:

UserName

這樣建立用戶:

Membership.CreateUser("UserName", "P@ssw0rd", "userName@emailAddress")

注意:你可以設置 requiresUniqueEmail "true" 來確保所有用戶的 mail 地址不重複

4 、認證用戶

要認證用戶,你必須要建立一個登錄頁面,而它也就是唯一不需要驗證的頁面

可以使用以下方法建立登錄頁面:

l         ASP.NET 2.0 登錄控件,這個控件幾乎包含了所有涉及到的操作,它會自動連接配置過的 membership provider ,不需要寫任何代碼,登錄以後控件可以保存用戶信息,比如用加密過的 cookie 保存。

l         當然你也可以手動來用文本框完成這個過程,可以利用 Membership ValidateUser 來判斷登錄情況,登錄完成後你還需要用 FormsAuthentication 類來爲用戶的瀏覽器寫入 cookie ,下面是例子:

 

if (Membership.ValidateUser(userName.Text, password.Text))

{

  if (Request.QueryString["ReturnUrl"] != null)

  {

    FormsAuthentication.RedirectFromLoginPage(userName.Text, false);

  }

  else

  {

    FormsAuthentication.SetAuthCookie(userName.Text, false);

  }

}

else

{

  Response.Write("Invalid UserID and Password");

}

 

注意:上面兩種方式都是使用 Membership.CreateUser 方法

bool isValidUser = Membership.ValidateUser("UseName@DomainName", "P@ssw0rd");

 

attributeMapUsername="sAMAccountName"

 

bool isValidUser = Membership.ValidateUser("UserName", "P@ssw0rd", "userName@emailAddress")

 

使用 SQLMemberShipProvider

當在外網做驗證或者內網有沒有配置活動目錄的時候我們可以使用 SQLMembershipProvider 來作爲驗證的數據源,其實默認的設置就是使用 SQLMembershipProvider

基本步驟

按照如下的步驟來爲表單驗證啓用 SqlMembershipProvider

1 、配置表單認證

2 、按照 membership 數據庫

3 、建立用戶

4 、認證用戶

1 、省略。。。同 ActiveDirectoryMembershipProvider

2 、按照 membership 數據庫

在使用 SqlMembershipProvider 以前需要安裝一個 membership 數據庫,使用一個 SQL SERVER 管理員權限登錄到服務器,然後在 Visual Studio 2005 命令行模式下執行下面的語句

 

aspnet_regsql.exe -E -S localhost -A m

看下幾個參數:

-E 表明此帳號使用 windows 集成認證

-S 表明需要安裝數據庫的服務器名

-A m 表明自動爲 membership 建立相應的表和存儲過程

 

注意: Aspnet_regsql 工具同樣爲其他 ASP.NET 2.0 特性安裝數據庫,比如說成員管理, Profile ,個性化 Web Parts 還有 Web Events 等,當然都會有其他的命令,如果你不使用任何參數的話可以以想到模式運行程序,會允許你在安裝的過程中指定數據庫服務器和你需要安裝的組件

 

3 、配置 SqlMembershipProvider

Machine.config 其實默認就是使用 SQL Server Express 作爲 SqlMembershipProvider 的,如果你的數據庫不是運行在本機的,可以修改下配置

<connectionStrings>

  <add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />

</connectionStrings>

<system.web>

...

  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">

    <providers>

      <clear />

      <add

        name="SqlProvider"

        type="System.Web.Security.SqlMembershipProvider"

        connectionStringName="MySqlConnection"

        applicationName="MyApplication"

        enablePasswordRetrieval="false"

        enablePasswordReset="true"

        requiresQuestionAndAnswer="true"

        requiresUniqueEmail="true"

        passwordFormat="Hashed" />

    </providers>

  </membership>

 

更多信息看本文“ SqlProviderMembershipProvider 屬性配置”章節

Step 4. Create Users

4 、建立用戶:

省略。。。同 ActiveDirectoryMembershipProvider

5 、認證用戶:

省略。。。同 ActiveDirectoryMembershipProvider

 

ActiveDirectoryMembershipProvider 的屬性配置

1 顯示了 ActiveDirectoryMembershipProvider 的屬性,默認值和用途

1: ActiveDirectoryMembershipProvider 的屬性配置

(這部分不翻譯)

Attribute

Default Value

Notes

connectionStringName

 

Points to a connection string contained in the connection strings configuration section. This attribute is required because it points to the primary LDAP bind string that is used for create , update , get , and validate operations.

connectionUserName

 

Defines the user name used for authentication purposes when connecting to the directory. If this attribute is specified, the companion connectionPassword attribute must also be specified. This attribute is used to configure a set of credentials that can be used to connect to the directory (instead of using the process account or impersonation credentials that are in effect at the time the provider connects to the directory).

connectionPassword

 

Defines the password used for authentication purposes when connecting to the directory. If this attribute is specified, the companion connectionUserName attribute must also be specified. This attribute is used to configure a set of credentials that can be used to connect to the directory (instead of using the process account or impersonation credentials that are in effect at the time the provider connects to the directory).

connectionProtection

Secure

Defines the transport layer security options that are used when opening connections to the directory. This attribute can have a string value of "Secure" or "None" .

If set to "Secure" , the provider attempts to select the highest level of connection security available, based on the type of directory that the provider connects to. The protection is determined as follows:
SSL is first attempted because SSL is an option that works with both Active Directory and ADAM (ActiveDirectoryConnection
Protection.Ssl)
.
If SSL is not available and the provider is connecting to Active Directory or to a domain-joined ADAM instance, encrypt-sign-and-seal is used (ActiveDirectoryConnection
Protection.SignAndSeal
).
If neither SSL nor encrypt-sign-seal is available, the provider generates a ProviderException , stating that it could not automatically select a secure connection to the configured directory.

enablePasswordReset

False

Controls whether or not a password can be reset. For security reasons, with the ActiveDirectoryMembershipProvider , this attribute can only be set to true if all of the following have been set:
requiresQuestionAndAnswer is set to true .
passwordQuestion , passwordAnswer , attributeMapFailedPasswordAnswer
Count
, attributeMapFailedPassword
AnswerTime
, and attributeMapFailed
PasswordAnswerLockoutTime
have been mapped to attributes in the directory.
Note : Even if this attribute is set to true , password resets are allowed only if the credentials used to perform the reset have Administrator privileges in Active Directory..

enableSearchMethods

False

Allows an administrator to set whether or not search-oriented methods can be called on the provider instance. Because methods such as Find* and GetAllUsers can be very expensive, the default value for this attribute is false .
The following methods throw a NotSupportedException if they are called when this attribute is set to false :
FindUsersByName
FindUsersByEmail
GetAllUsers

requiresQuestionAnd
Answer

False

Determines whether a password question and answer are required for a password reset.

For security reasons, with ActiveDirectoryMembership
Provider
, this attribute can only be set to true if all of the following have been set:
attributeMapPasswordQuestion , attributeMapPasswordAnswer , attributeMapFailedPasswordAnswerCount , attributeMapFailedPasswordAnswerTime , and attributeMapFailedPasswordAnswerLockoutTime

applicationName

/

For this provider, applicationName is included for completeness with other providers. Internally, it does not matter what value is placed here because the application name is not used. The maximum value is 256 characters.

requiresUniqueEmail

False

Specifies whether the e-mail values used in the application must be unique.

maxInvalidPassword
Attempts

5

Indicates the number of failed password attempts or failed password answer attempts allowed before a user's account is locked. When the number of failed attempts equals the value set in this attribute, the user's account is locked out.

For the Active Directory provider, this attribute applies only to managing resets that use a password answer. Active Directory manages bad password attempts internally.

passwordAttempt
Window

10

Indicates the time window, in minutes, during which failed password attempts and failed password answer attempts are tracked.

For the Active Directory provider, this attribute applies only to managing resets that use a password answer. Active Directory manages bad password attempts internally.

passwordAnswer
AttemptLockout
Duration

30

Specifies the duration, in minutes, that a lockout due to a bad password answer is considered still in effect. Because Active Directory uses the concept of timing out bad password lockouts, this attribute is necessary to support a similar concept of timing bad password answer attempts.

minRequiredPassword
Length

7

Specifies the minimum number of characters required in a password. The value can be from 1 to 128.

minRequiredNonAlpha
numericCharacters

1

Specifies the minimum number of non-alphanumeric characters required in a password. This configuration attribute cannot be set to a value greater than the value of the minRequiredPasswordLength . This means the configuration setting must be in the range of
0–minRequiredPasswordLength , inclusive of minRequiredPasswordLength .

passwordStrength
RegularExpression

""

Provides a valid regular expression that the provider will use as part of password strength validation.

attributeMapUsername

userPrincipalName

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
The only directory attributes for mapping to a username if you are using Active Directory are userPrincipalName or sAMAccountName . The only allowed directory attributes for mapping to username if you are using ADAM is userPrincipalName .

attributeMapEmail

Mail

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

attributeMapPassword
Question

UNDEFINED

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

attributeMapPassword
Answer

UNDEFINED

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

attributeMapFailed
PasswordAnswerCount

UNDEFINED

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

attributeMapFailed
PasswordAnswerTime

UNDEFINED

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

attributeMapFailed
PasswordAnswer
LockoutTime

UNDEFINED

Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

如果要啓用取回密碼你需要在 <providers > 後增加 <add > 設置 attributeMapPasswordQuestion attributeMapPasswordAnswer 屬性來增加 ActiveDirectoryMembershipProvider 詳細見 How To: Use Forms Authentication with Active Directory in ASP.NET 2.0 .

SqlMembershipProvider Configuration Attributes

SqlMembershipProvider 屬性配置

2 顯示了 SqlMembershipProvider 的屬性,默認值和用途

2. SqlMembershipProvider 屬性配置

屬性

默認

用途

connectionStringName

 

SQL SERVER 的連接字符串

enablePasswordReset

False

密碼能否重置
安全原因,只有當
requiresQuestionAndAnswer
設置爲 true 的時候你纔可以設置 enablePasswordReset true

requiresQuestionAnd
Answer

False

是否需要啓用取回密碼

applicationName

/

設置了它可以讓多個應用程序在數據庫內有所區分,不需要爲每個應用建立一個數據庫了

requiresUniqueEmail

False

郵件地址是否需要唯一

maxInvalidPassword
Attempts

5

密碼輸入錯誤幾次就會鎖定用戶

passwordAttempt
Window

10

每分鐘可以失敗的次數

passwordFormat

 

密碼方式 Clear , Encrypted , Hashed . 第一種是明文存儲,效率比較高,但是 SQL SERVER 中能直接讀取密碼,不安全 . 第二種是不可逆加密,需要一定的加密換算過程,但是比較安全 . 第三種是可逆加密,密碼不能找回

minRequiredPassword
Length

7

指定至少密碼需要幾位

minRequiredNonAlpha
numericCharacters

1

指定需要是非數字字母作爲密碼的位數,不能大於 minRequiredPassword
Length

passwordStrength
RegularExpression

""

指定強度計算的正則表達式

Membership

3 列出了一些 Membership 類重要的一些方法參數和用法

3. Membership 類方法

方法名

參數

備註

CreateUser

string username 創建的用戶名 .
string password
新用戶密碼
string email
新用戶 mail 地址
string passwordQuestion
string passwordAnswer
bool IsApproved
object providerUserKey

 

DeleteUser

string username 需要刪除的用戶名
bool removeAllRelatedData

返回 true 表示刪除, false 表示沒有找到

FindUsersByName

string usernameToMatch
int pageIndex
int pageSize

返回找到的用戶的集合,支持通配符 "* ", "% " "_ ".

FindUsersByEmail

string emailToMatch
int pageIndex
int pageSize

 

GeneratePassword

int length
Int numberOfNonAlpha
NumericCharacters

 

GetAllUsers

int pageIndex
int pageSize

返回用戶記錄集

GetNumberOfUsersOnline

None

返回在線的用戶,活動目錄不支持

GetUsernameByEmail

string email 需要查找的用戶的 mail 地址

 

UpdateUser

MembershipUser user 需要更新的用戶名

 

ValidateUser

string username 需要驗證的用戶名
string password
需要驗證的密碼

 

注意   GetAllUsers 方法在 RTM 版本的 .NET Framework 2.0 會取消

 

特別注意

默認情況下表單認證的票據傳輸是明文的,爲了防止票據被盜竊,我們還是建議你爲服務器啓用 SSL 。設置 requireSSL 屬性爲 true 來啓用 SSL ,下面的例子顯示了怎麼啓用 SSL ,還有不管用戶使用 http 還是 https 形式的 url 進入網站都能啓用,你可以嘗試登錄到 loginUrl 指定的頁面看看,但是需要保證這個頁面是沒有任何約束的

<configuration>

  <system.web>

    <authentication mode="Forms">

        <forms loginUrl="https://myserver/mywebapp/secure/Login.aspx"

               protection="All"

               timeout="30"

               name="AppNameCookie"

               path="/FormsAuth"

               requireSSL="true"

               slidingExpiration="true"

               defaultUrl="default.aspx"

               cookieless="UseCookies"

               enableCrossAppRedirects="false"/>

    </authentication>

 

    <!— 禁止沒有權限的用戶 -->

    <authorization>

       <deny users="?" />

       <allow users="*" />

     </authorization>

  </system.web>

</configuration>

 

<!— 使得登錄頁面沒有任何限制 -->

<location path="secure">

  <system.web>

    <authorization>

       <allow users="*" />

     </authorization>

  </system.web>

</location>

發佈了19 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章