摘要:
本文介绍了怎么在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"
因为所有用户名都需要按照下面的格式:
[email protected]
如果手动使用membership.createuser方法来创建用户,这么做
membership.createuser("[email protected]", "[email protected]", "[email protected]");
你也能设置config文件来改变映象方式:
attributemapusername="samaccountname"
如果这样设置的话,用户名就如下格式:
username
这样建立用户:
membership.createuser("username", "[email protected]", "[email protected]")
注意:你可以设置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("[email protected]", "[email protected]");
attributemapusername="samaccountname"
bool isvaliduser = membership.validateuser("username", "[email protected]", "[email protected]")
使用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: |
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 | "" | 指定强度计算的正则表达式 |
membership类
表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"
&, nbsp; 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>
翻译原文:http://lovecherry.cnblogs.com/archive/2005/12/05/291092.html
英文原文:http://msdn.microsoft.com/library/en-us/dnpag2/html/paght000022.asp
新闻热点
疑难解答
图片精选