国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

怎么在ASP.NET 2.0中使用Membership

2024-07-10 13:06:30
字體:
供稿:網(wǎng)友

摘要:

本文介紹了怎么在asp.net 2.0中使用membership新特性,并且介紹了怎么使用兩種不同的membershipprovideractivedirectorymembershipprovidersqlmembershipprovider,前者是基于微軟活動目錄服務(wù)存儲用戶信息的,或者是基于sql server存儲的。2.0中的這個(gè)新機(jī)制大大減少了站點(diǎn)用戶認(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àn)榉阑饓蛘咝枰m應(yīng)不同的瀏覽器等原因不能使用windows集成認(rèn)證的話,這個(gè)時(shí)候你可以選擇使用activedirectorymembershipprovider實(shí)現(xiàn)表單認(rèn)證

基本的步驟如下

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

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

2、配置activedirectorymembershipprovider

3、建立用戶

4、認(rèn)證用戶

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

要實(shí)現(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í)啟用數(shù)據(jù)來源驗(yàn)證和加密

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

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

·                     requiressl 設(shè)置成"false"表示關(guān)閉cookiessl加密

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

·                     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é)點(diǎn)來為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(在這個(gè)例子中是membershipadprovider),如果需要為機(jī)器級別改變這個(gè)屬性,%windir%/microsoft.net/framework/{version}/config/machine.config文件中改寫原有的aspnetsqlmembershipprovideraspnetsqlmembershipprovider是使用sqlmembershipprovider/app_data目錄中的sql server express數(shù)據(jù)庫來存放用戶信息的機(jī)制

3、建立用戶

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

·                     打開vs.net2005website菜單,點(diǎn)擊asp.net configuration,然后在安全里面進(jìn)行設(shè)置

·                     建立一個(gè)asp.net頁面,放入一個(gè)createuserwizard控件,這個(gè)控件使用配置過的membership provider來實(shí)現(xiàn)建立用戶的過程

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

 

注意:其實(shí)所有這些方法最終還是使用membership.createuser來建立用戶

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

attributemapusername="userprincipalname"

因?yàn)樗杏脩裘夹枰凑障旅娴母袷剑?/span>

[email protected]

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

membership.createuser("[email protected]", "[email protected]", "[email protected]");

 

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

attributemapusername="samaccountname"

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

username

這樣建立用戶:

membership.createuser("username", "[email protected]", "[email protected]")

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

4、認(rèn)證用戶

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

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

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

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

 

attributemapusername="samaccountname"

 

bool isvaliduser = membership.validateuser("username", "[email protected]", "[email protected]")

 

使用sqlmembershipprovider

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

基本步驟

按照如下的步驟來為表單驗(yàn)證啟用sqlmembershipprovider

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

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

3、建立用戶

4、認(rèn)證用戶

1、省略。。。同activedirectorymembershipprovider

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

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

 

aspnet_regsql.exe -e -s localhost -a m

看下幾個(gè)參數(shù):

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

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

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

 

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

 

3、配置sqlmembershipprovider

machine.config其實(shí)默認(rèn)就是使用sql server express作為sqlmembershipprovider的,如果你的數(shù)據(jù)庫不是運(yùn)行在本機(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í)候你才可以設(shè)置enablepasswordresettrue

requiresquestionand
answer

false

是否需要啟用取回密碼

applicationname

/

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

requiresuniqueemail

false

郵件地址是否需要唯一

maxinvalidpassword
attempts

5

密碼輸入錯(cuò)誤幾次就會鎖定用戶

passwordattempt
window

10

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

passwordformat

 

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

minrequiredpassword
length

7

指定至少密碼需要幾位

minrequirednonalpha
numericcharacters

1

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

passwordstrength
regularexpression

""

指定強(qiáng)度計(jì)算的正則表達(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需要?jiǎng)h除的用戶名
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需要驗(yàn)證的用戶名
string password
需要驗(yàn)證的密碼

 

注意  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指定的頁面看看,但是需要保證這個(gè)頁面是沒有任何約束的

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

         &, nbsp;     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>

  

  翻譯原文:http://lovecherry.cnblogs.com/archive/2005/12/05/291092.html

  英文原文:http://msdn.microsoft.com/library/en-us/dnpag2/html/paght000022.asp


注冊會員,創(chuàng)建你的web開發(fā)資料庫,
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 汤阴县| 利川市| 陆河县| 彭州市| 积石山| 临猗县| 澎湖县| 深州市| 呼玛县| 舒兰市| 仁寿县| 屏边| 宁河县| 上蔡县| 怀柔区| 克东县| 安福县| 信阳市| 云和县| 万山特区| 当阳市| 常熟市| 大渡口区| 松阳县| 石城县| 泽普县| 安丘市| 福建省| 漳浦县| 婺源县| 稻城县| 疏勒县| 祁连县| 旬阳县| 达拉特旗| 久治县| 潍坊市| 高陵县| 郧西县| 栾川县| 谢通门县|