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
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: |
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: |
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. |
requiresQuestionAnd |
False |
Determines whether a password question and answer are required for a password reset. For security reasons, with ActiveDirectoryMembership |
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 |
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 |
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 |
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 |
7 |
Specifies the minimum number of characters required in a password. The value can be from 1 to 128. |
minRequiredNonAlpha |
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 |
passwordStrength |
"" |
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. |
attributeMapEmail |
|
Defines the mapping from a property on a MembershipUser object to an attribute within the directory. |
attributeMapPassword |
UNDEFINED |
Defines the mapping from a property on a MembershipUser object to an attribute within the directory. |
attributeMapPassword |
UNDEFINED |
Defines the mapping from a property on a MembershipUser object to an attribute within the directory. |
attributeMapFailed |
UNDEFINED |
Defines the mapping from a property on a MembershipUser object to an attribute within the directory. |
attributeMapFailed |
UNDEFINED |
Defines the mapping from a property on a MembershipUser object to an attribute within the directory. |
attributeMapFailed |
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 |
密碼能否重置 |
requiresQuestionAnd |
False |
是否需要啓用取回密碼 |
applicationName |
/ |
設置了它可以讓多個應用程序在數據庫內有所區分,不需要爲每個應用建立一個數據庫了 |
requiresUniqueEmail |
False |
郵件地址是否需要唯一 |
maxInvalidPassword |
5 |
密碼輸入錯誤幾次就會鎖定用戶 |
passwordAttempt |
10 |
每分鐘可以失敗的次數 |
passwordFormat |
|
密碼方式 Clear, Encrypted, 和Hashed. 第一種是明文存儲,效率比較高,但是SQL SERVER中能直接讀取密碼,不安全. 第二種是不可逆加密,需要一定的加密換算過程,但是比較安全.第三種是可逆加密,密碼不能找回 |
minRequiredPassword |
7 |
指定至少密碼需要幾位 |
minRequiredNonAlpha |
1 |
指定需要是非數字字母作爲密碼的位數,不能大於minRequiredPassword |
passwordStrength |
"" |
指定強度計算的正則表達式 |
表3列出了一些Membership類重要的一些方法參數和用法
表3. Membership 類方法
方法名 |
參數 |
備註 |
CreateUser |
string username–創建的用戶名. |
|
DeleteUser |
string username–需要刪除的用戶名 |
返回true表示刪除,false表示沒有找到 |
FindUsersByName |
string usernameToMatch |
返回找到的用戶的集合,支持通配符 "*", "%" 和 "_". |
FindUsersByEmail |
string emailToMatch |
|
GeneratePassword |
int length |
|
GetAllUsers |
int pageIndex |
返回用戶記錄集 |
GetNumberOfUsersOnline |
None |
返回在線的用戶,活動目錄不支持 |
GetUsernameByEmail |
string email–需要查找的用戶的mail地址 |
|
UpdateUser |
MembershipUser user–需要更新的用戶名 |
|
ValidateUser |
string username–需要驗證的用戶名 |
|
注意 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>