posts - 5,  comments - 5,  trackbacks - 0

          摘要:

          本文介紹了怎么在ASP.NET 2.0中使用Membership新特性,并且介紹了怎么兩種不同的Membership的Provider:ActiveDirectoryMembershipProvider和SqlMembershipProvider,前者是基于微軟活動目錄服務(wù)存儲用戶信息的,或者是基于SQL SERVER存儲的。2.0中的這個新機(jī)制大大減少了站點用戶認(rèn)證模塊的代碼量。

          目錄:

          學(xué)習(xí)目的

          使用ActiveDirectoryMembershipProvider

          使用SqlMembershipProvider

          ActiveDirectoryMembershipProvider的一些設(shè)置參數(shù)

          SqlMembershipProvider的一些設(shè)置參數(shù)

          Membership 的一些API

          學(xué)習(xí)目的:

          學(xué)會使用Membership進(jìn)行表單認(rèn)證

          學(xué)會設(shè)置ActiveDirectoryMembershipProvider

          學(xué)會使用ActiveDirectoryMembershipProvider建立認(rèn)證用戶

          學(xué)會設(shè)置SqlMembershipProvider

          學(xué)會建立SQL SERVER Membership數(shù)據(jù)庫

          學(xué)會使用SqlMembershipProvider建立認(rèn)證用戶

          使用ActiveDirectoryMembershipProvider

          如果用戶信息是存儲在活動目錄中,而你的內(nèi)網(wǎng)程序又因為防火墻或者需要適應(yīng)不同的瀏覽器等原因不能使用windows集成認(rèn)證的話,這個時候你可以選擇使用ActiveDirectoryMembershipProvider實現(xiàn)表單認(rèn)證

          基本的步驟如下

          按照以下步驟來用ActiveDirectoryMembershipProvider實現(xiàn)asp.net程序的用戶表單認(rèn)證

          1、配置表單認(rèn)證

          2、配置ActiveDirectoryMembershipProvider

          3、建立用戶

          4、認(rèn)證用戶

          1、配置表單認(rèn)證

          要實現(xiàn)表單認(rèn)證需要設(shè)置<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 設(shè)置成"All"表示為認(rèn)證憑據(jù)同時啟用數(shù)據(jù)來源驗證和加密

          ·                     Timeout 指定了認(rèn)證的生存時間

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

          ·                     requireSSL 設(shè)置成"false"表示關(guān)閉cookie的SSL加密

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

          ·                     defaultUrl 就是設(shè)置程序的首頁

          ·                     cookieless 設(shè)置成"UseCookies"表示使用cookie來傳遞認(rèn)證票據(jù)

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

          按照下面的例子為<authentication> 增加<authorization>塊,表明只有登錄過的用戶才能進(jìn)入程序否則會被轉(zhuǎn)到前面loginUrl設(shè)置的頁面

          <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>子節(jié)點來為membership指定ActiveDirectoryMembershipProvider,活動目錄中存儲用戶信息的連接字符串如下格式LDAP:// server/userdn,

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

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

           

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

          3、建立用戶

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

          ·                     打開vs.net2005的Website菜單,點擊ASP.NET Configuration,然后在安全里面進(jìn)行設(shè)置

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

          ·                     手動拖放填寫用戶名和密碼的文本框然后使用Membership API的CreateUser方法來實現(xiàn)

           

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

          默認(rèn)配置的ActiveDirectoryMembershipProvider使用UPNs來進(jìn)行名字印象,如下

          attributeMapUsername="userPrincipalName"

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

          UserName@DomainName

          如果手動使用Membership.CreateUser方法來創(chuàng)建用戶,這么做

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

           

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

          attributeMapUsername="sAMAccountName"

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

          UserName

          這樣建立用戶:

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

          注意:你可以設(shè)置requiresUniqueEmail為"true"來確保所有用戶的mail地址不重復(fù)

          4、認(rèn)證用戶

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

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

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

          l         當(dāng)然你也可以手動來用文本框完成這個過程,可以利用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

          當(dāng)在外網(wǎng)做驗證或者內(nèi)網(wǎng)有沒有配置活動目錄的時候我們可以使用SQLMembershipProvider來作為驗證的數(shù)據(jù)源,其實默認(rèn)的設(shè)置就是使用SQLMembershipProvider的

          基本步驟

          按照如下的步驟來為表單驗證啟用SqlMembershipProvider

          1、配置表單認(rèn)證

          2、按照membership數(shù)據(jù)庫

          3、建立用戶

          4、認(rèn)證用戶

          1、省略。。。同ActiveDirectoryMembershipProvider

          2、按照membership數(shù)據(jù)庫

          在使用SqlMembershipProvider以前需要安裝一個membership數(shù)據(jù)庫,使用一個SQL SERVER管理員權(quán)限登錄到服務(wù)器,然后在Visual Studio 2005命令行模式下執(zhí)行下面的語句

           

          aspnet_regsql.exe -E -S localhost -A m

          看下幾個參數(shù):

          -E 表明此帳號使用windows集成認(rèn)證

          -S 表明需要安裝數(shù)據(jù)庫的服務(wù)器名

          -A m 表明自動為membership建立相應(yīng)的表和存儲過程

           

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

           

          3、配置SqlMembershipProvider

          Machine.config其實默認(rèn)就是使用SQL Server Express作為SqlMembershipProvider的,如果你的數(shù)據(jù)庫不是運行在本機(jī)的,可以修改下配置

          <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屬性配置”章節(jié)

          Step 4. Create Users

          4、建立用戶:

          省略。。。同ActiveDirectoryMembershipProvider

          5、認(rèn)證用戶:

          省略。。。同ActiveDirectoryMembershipProvider

           

          ActiveDirectoryMembershipProvider的屬性配置

          表1顯示了ActiveDirectoryMembershipProvider的屬性,默認(rèn)值和用途

          表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>設(shè)置attributeMapPasswordQuestion 和 attributeMapPasswordAnswer 屬性來增加ActiveDirectoryMembershipProvider詳細(xì)見How To: Use Forms Authentication with Active Directory in ASP.NET 2.0.

          SqlMembershipProvider Configuration Attributes

          SqlMembershipProvider屬性配置

          表2顯示了SqlMembershipProvider的屬性,默認(rèn)值和用途

          表 2. SqlMembershipProvider屬性配置

          屬性

          默認(rèn)

          用途

          connectionStringName

           

          SQL SERVER的連接字符串

          enablePasswordReset

          False

          密碼能否重置
          安全原因,只有當(dāng)
          requiresQuestionAndAnswer 設(shè)置為 true的時候你才可以設(shè)置enablePasswordReset為true

          requiresQuestionAnd
          Answer

          False

          是否需要啟用取回密碼

          applicationName

          /

          設(shè)置了它可以讓多個應(yīng)用程序在數(shù)據(jù)庫內(nèi)有所區(qū)分,不需要為每個應(yīng)用建立一個數(shù)據(jù)庫了

          requiresUniqueEmail

          False

          郵件地址是否需要唯一

          maxInvalidPassword
          Attempts

          5

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

          passwordAttempt
          Window

          10

          每分鐘可以失敗的次數(shù)

          passwordFormat

           

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

          minRequiredPassword
          Length

          7

          指定至少密碼需要幾位

          minRequiredNonAlpha
          numericCharacters

          1

          指定需要是非數(shù)字字母作為密碼的位數(shù),不能大于minRequiredPassword
          Length

          passwordStrength
          RegularExpression

          ""

          指定強(qiáng)度計算的正則表達(dá)式

          Membership類

          表3列出了一些Membership類重要的一些方法參數(shù)和用法

          表3. Membership 類方法

          方法名

          參數(shù)

          備注

          CreateUser

          string username–創(chuàng)建的用戶名.
          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 會取消

           

          特別注意

          默認(rèn)情況下表單認(rèn)證的票據(jù)傳輸是明文的,為了防止票據(jù)被盜竊,我們還是建議你為服務(wù)器啟用SSL。設(shè)置requireSSL屬性為true來啟用SSL,下面的例子顯示了怎么啟用SSL,還有不管用戶使用http還是https形式的url進(jìn)入網(wǎng)站都能啟用,你可以嘗試登錄到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>

           

              <!—禁止沒有權(quán)限的用戶 -->

              <authorization>

                 <deny users="?" />

                 <allow users="*" />

               </authorization>

            </system.web>

          </configuration>

           

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

          <location path="secure">

            <system.web>

              <authorization>

                 <allow users="*" />

               </authorization>

            </system.web>

          </location>

          posted on 2007-07-06 09:01 曾科 閱讀(476) 評論(0)  編輯  收藏 所屬分類: ASP.NET
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(3)

          隨筆檔案

          文章分類

          文章檔案

          相冊

          .net

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 金秀| 定日县| 同仁县| 比如县| 黔江区| 厦门市| 曲周县| 巴彦淖尔市| 石屏县| 扶沟县| 原平市| 上林县| 通渭县| 望谟县| 高雄县| 沂源县| 安宁市| 聂拉木县| 镇巴县| 拉孜县| 长顺县| 泰安市| 嘉禾县| 富源县| 固镇县| 习水县| 安陆市| 德江县| 衡阳市| 宜黄县| 乐昌市| 扬中市| 吉林省| 邯郸市| 丹巴县| 古交市| 开江县| 平泉县| 江阴市| 宁阳县| 通山县|