All articles| All Pictures| All Softwares| All Video| Go home page| Write articles| Upload pictures

Reading number is top 10 articles
SQLSERVER2005的混和身份验证模式的设置以及SA登陆问题_[SQL Server教程]
如何在十天内学会php之第一天_[PHP教程]
PHP Shell的编写(改进版)_[PHP教程]
请慎用ASP.Net的validateRequest=“false”_.net资料_编程技术
在asp.net2.0页面部分缓存中使用ControlCachePolicy类
关于ASP.NET2.0,中的用户控件编程使用_.net资料_编程技术
Ajax无刷新实现图片切换特效_.net资料_编程技术
无废话C#设计模式之六:Builder_.net资料_编程技术
GridView的各种用法(2)_[Asp.Net教程]
ASP.NET,2.0中客户端脚本使用总结_.net资料_编程技术
Reading number is top 10 pictures
Photographed the passion of the clients and prostitutes in the sex trade picture2
漂亮的跳舞妹妹2
Sora aoi in China1
Perfect small Laurie1
宝贝系列
Discharge accidentally Actresses by the breast1
Hunan road lawenforcement vehicle pursue overload car caused the car turn and man is died
On the verge of extinction of the beach1
A man's favorite things8
Born After 90 Beijing sports university campus flower photos2
Download software ranking
Proficient in Eclipse
Unix video tutorial10
Boxer's Top ten classic battle10
功夫熊猫2(上集)
软件工程思想
网页特效实例大全
实战黑客不求人
虚拟机5.5.3版
Unix video tutorial20
Boxer vs Yellow5
归海一刀 published in(发表于) 2014/1/30 1:12:14 Edit(编辑)
温故知新ASP.NET,2.0(C#)(6),-,Membership&RoleManager_[Asp.Net教程]

温故知新ASP.NET,2.0(C#)(6),-,Membership&RoleManager_[Asp.Net教程]

温故知新ASP.NET 2.0(C#)(6) - Membership&RoleManager_[Asp.Net教程]

温故知新ASP.NET 2.0(C#)(6) - Membership&RoleManager(成员资格和角色管理)



介绍
现在 ASP.NET 2.0 提供了对成员资格(用户名/密码凭据存储)和角色管理服务的内置支持。由于所有这些服务都是提供程序驱动的(Provider),因此可以方便地用您自己的自定义实现替换。



关键
1、基于Windows的身份验证将元素下的 设置为 Windows;基于Forms的身份验证将元素下的 设置为 Forms。


2、基于Forms的身份验证时,设置元素下的 元素的 子元素,示例如下,仅为说明


protection="All" timeout="30" path="/" requireSSL="false"
slidingExpiration="true" enableCrossAppRedirects="false"
cookieless="UseDeviceProfile">



元素的属性说明如下
1) cookieless - 身份验证可以将 Forms 身份验证票存储在 Cookie 中也可以以无 Cookie 的表示形式存储在 URL 上。有效值如下:
·UseDeviceProfile - 默认值表示 ASP.NET 根据预先计算得到的浏览器配置文件来确定存储票证的位置。
·AutoDetect - 选项使 ASP.NET 动态确定浏览器是否支持 Cookie。
·UseUri - 强制实施无 Cookie 票证
·UseCookies - 强制实施有 Cookie 票证。
2) defaultUrl - 指定在成功登录后,请求将重定向到的默认 URL。
3) domain - 指定包含 Forms 身份验证票的 HttpCookie 的 Domain 属性的值。显式设置此属性可使应用程序共享同一个 Cookie,前提是这些应用程序共享某个 DNS 命名空间的一个公共部分(例如,如果 domain 属性设置为“cnblogs.com”,则 webabcd.cnblogs.com 和 dudu.cnblogs.com可以共享一个 Cookie)。
4) enableCrossAppRedirects - Forms 身份验证允许以查询字符串变量或窗体 POST 变量的形式在应用程序之间传递 Forms身份验证票。将此属性设置为 true 可使 FormsAuthenticationModule 能够从查询字符串或窗体 POST 变量提取票证。
5) loginUrl - 指定未经身份验证的用户的请求将被重定向到的 URL。该 URL 可以在同一台计算机上或在远程计算机上。如果是在远程计算机上,则两台计算机上 machineKey 配置元素中的 decryptionkey 和 validationKey 属性都需要使用相同的值。
6) name - 用于身份验证的 HTTP Cookie 的名称。注意,如果多个应用程序需要在一台计算机上使用基于窗体的身份验证服务,并且每个应用程序都希望由应用程序隔离 Forms 身份验证 Cookie,则每个应用程序都应配置一个唯一的 Cookie 值。为避免在 URL 中产生依赖项,在设置身份验证 Cookie 时,ASP.NET 还使用“/”作为 Path 值,以便将这些 Cookie 发送回站点上的每个应用程序。
7) path - 用于发出的 Cookie 的路径。默认值为“/”,以避免路径中大小写不匹配的造成的困难,因为在返回 Cookie 时,浏览器是严格区分大小写的。共享服务器环境中的应用程序应使用此指令来维护专用 Cookie。(它们还可以使用 API 在运行时指定路径来发出 Cookie。)
8) protection - 用于保护 Cookie 数据的方法。有效值如下:
·All - 同时使用数据验证和加密来保护 Cookie。所配置的数据验证算法是基于 元素的。如果密钥足够长(48 个字符),默认情况下将使用 AES 进行加密。All 是默认(和建议)值。
·None - 用于仅将 Cookie 用于个性化设置并且安全性要求不高的站点。加密和验证都可以被禁用。尽管以此方式使用 Cookie 需谨慎,但对于使用 .NET Framework 实现个性化设置的任何方法,此设置提供了最佳性能。
·Encryption - 使用 AES、TripleDES 或 DES 加密 Cookie,但不对 Cookie 进行数据验证。这类 Cookie 容易受到精心选择的纯文本的攻击。
·Validation - 不加密 Cookie 的内容,但验证 Cookie 数据在传输过程中是否未被更改。若要创建 Cookie,验证密钥在缓冲区中与 Cookie 数据连接,并且计算出 MAC 并将其追加到输出的 Cookie。
9) requireSSL - 如果设置为 true,则 Forms 身份验证会设置 Forms 身份验证 Cookie 的安全位。兼容的浏览器只将 Cookie 通过 SSL 连接发送回 ASP.NET。注意,如果使用无 Cookie Forms 身份验证,则此设置无效。
10) slidingExpiration - 如果设置为 true,则 Forms 身份验证将定期更新 Forms 身份验证票的生存期。无论票证是包含在 Cookie 中,还是以无 Cookie 的格式包含在 URL 中,都会进行此操作。
11) timeout - 时间量(以整数分钟为单位),经过该时间量之后,Cookie 则会过期。默认值是 30。超时属性是一个可调值,从收到上次请求的时间开始计算,它将在 n 分钟后过期。为了避免对性能产生负面影响,也为了避免那些打开了 Cookie 警告的应用程序产生多个浏览器警告,Cookie 在超时时间过半时更新。(这意味着在某些情况下可能会出现精度损失。) (注意:createPersistentCookie为true的话,则该属性失效,过期时间将为50年)


3、授权用户和角色设置元素下的元素,示例如下,仅为说明







注:可以把授权用户和角色设置的配置写在某个文件夹内,则所做的配置只作用于该文件夹内,自动继承外面的配置。
allow - 允许
deny - 拒绝
users - 用户(多用户用逗号隔开)
roles - 角色(多角色用逗号隔开)
verb - 指定http方法,post或get
* - 所有用户
? - 匿名(未经过身份验证的)用户


4、分路径设置授权用户和角色设置,示例如下,仅为说明

















元素的path属性可以是文件夹也可以是某一文件


5、元素设置,示例如下,仅为说明



type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="SqlConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="3"
minRequiredPasswordLength="3"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />


enablePasswordRetrieval - 是否可以检索用户密码(总是false)
enablePasswordReset - 是否允许用户重置其密码
requiresQuestionAndAnswer - 是否要求在创建用户时提供密码提示问题和答案
applicationName - 自定义成员资格提供程序的应用程序的名称
requiresUniqueEmail - 电子邮件地址是否必须是唯一的
passwordFormat - 存储的密码的格式
maxInvalidPasswordAttempts - 指定允许的无效密码或无效密码提示问题答案尝试的次数。当无效尝试的次数达到配置的值时,将锁定该成员资格用户
minRequiredPasswordLength - 密码所要求的最小长度
minRequiredNonalphanumericCharacters - 有效密码中必须包含的最少特殊字符数
passwordAttemptWindow - 跟踪失败的尝试所用的时间(以分钟为单位)。每当发生另一次失败时都将重置窗口。如果达到了允许的无效密码或密码提示问题答案的最大尝试次数,将锁定成员资格用户
passwordStrengthRegularExpression - 用于验证密码的正则表达式


6、元素设置,示例如下,仅为说明
enabled="true"
cacheRolesInCookie="true"
cookieName=".VS2005_Role"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All">

name="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlConnectionString"
applicationName="/" />


各属性详细说明参看MSDN,索引处查找“roleManager 元素”


7、使用加密密码






使用FormsAuthentication.HashPasswordForStoringInConfigFile(String password, String passwordFormat)生成密码
Clear - 密码以明文形式存储
SHA1 - 密码存储为 SHA1 摘要
MD5 - 密码存储为 MD5 摘要


8、使用用户帐户模拟,在元素下加如下元素

9、常用的就是如下这些东东
System.Web.Security.Membership,System.Web.Security.MembershipUser,System.Web.Security.Roles,Page.User
FormsAuthentication.RedirectFromLoginPage,FormsAuthentication.SetAuthCookie,FormsAuthentication.SignOut
重写那些Provider的话,参看源码中微软提供的示例



示例
读取用户名和验证类型
Security/Test.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs"
Inherits="Security_Test" Title="读取用户名和验证类型" %>




用户名称:
<%=User.Identity.Name %>


验证类型:
<%=User.Identity.AuthenticationType %>



Membership测试
App_Code/User.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.ComponentModel;


/**////


/// User 的摘要说明
///

[DataObject(true)]
public class User
{
public User()
{
//
// TOD 在此处添加构造函数逻辑
//
}


/**////


/// 获得所有用户
///

///
[DataObjectMethod(DataObjectMethodType.Select, true)]
public MembershipUserCollection GetMembers()
{
MembershipUserCollection muc = Membership.GetAllUsers();
return muc;
}


/**////


/// 删除用户
///

///
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public void DeleteMember(string username)
{
Membership.DeleteUser(username, true);
}
}


Security/User.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="User.aspx.cs"
Inherits="Security_User" Title="Membership测试" %>







用户名:



密&nbsp;&nbsp;&nbsp;&nbsp;码:



onClick="btnSubmit_Click" />



DataSourceID="ObjectDataSource1">


SortExpression="ProviderName" />

ReadOnly="True" SortExpression="LastPasswordChangedDate" />
SortExpression="PasswordQuestion" />
SortExpression="IsLockedOut" />



SortExpression="CreationDate" />

SortExpression="LastLockoutDate" />




TypeName="User" DeleteMethod="DeleteMember">






备注:

用户和角色之间的操作如下

Roles.AddUserToRole - 向角色添加用户

Roles.RemoveUserFromRole - 从角色删除用户

Roles.GetRolesForUser - 用户所属的角色列表



Security/User.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Security_User : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}


protected void btnSubmit_Click(object sender, EventArgs e)
{
MembershipCreateStatus status;
Membership.CreateUser(txtUsername.Text.Trim(), txtPassword.Text.Trim(), null, null, null, true, out status);


string strInsertMessage = "";


switch (status)
{
case MembershipCreateStatus.Success:


break;
case MembershipCreateStatus.DuplicateUserName:
strInsertMessage = "用户名重复";
break;
case MembershipCreateStatus.InvalidUserName:
strInsertMessage = "用户名输入错误";
break;
case MembershipCreateStatus.InvalidPassword:
strInsertMessage = "密码输入不符合要求";
break;
default:
strInsertMessage = "出现未知错误";
break;
}


if (strInsertMessage != "")
{
lblMsg.Text = strInsertMessage;
}
else
{
lblMsg.Text = "注册成功";
GridView1.DataBind();
}
}
}



RoleManager测试
App_Code/Role.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.Collections.Generic;
using System.ComponentModel;


/**////


/// Role 的摘要说明
///

[DataObject(true)]
public class Role
{
public Role()
{
//
// TOD 在此处添加构造函数逻辑
//
}


/**////


/// 得到所有角色
///

/// 用户名称
///
[DataObjectMethod(DataObjectMethodType.Select, true)]
static public List GetRoles()
{
RoleData r = null;
List roleList = new List();
string[] ary = Roles.GetAllRoles();


foreach (string s in ary)
{
r = new RoleData();
r.RoleName = s;


roleList.Add(r);
}


return roleList;
}


/**////


/// 删除角色
///

/// 角色名称
[DataObjectMethod(DataObjectMethodType.Delete, true)]
static public void DeleteRole(string roleName)
{
MembershipUserCollection muc = Membership.GetAllUsers();
string[] allUserNames = new string[1];


foreach (MembershipUser mu in muc)
{
if (Roles.IsUserInRole(mu.UserName, roleName))
{
allUserNames[0] = mu.UserName;
Roles.RemoveUsersFromRole(allUserNames, roleName);
}
}
Roles.DeleteRole(roleName);
}
}


/**////


/// 角色的实体类
///

public class RoleData
{
protected string _roleName;


/**////


/// 角色名称 关键字
///

[DataObjectField(true)]
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
}


Security/Role.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Role.aspx.cs"
Inherits="Security_Role" Title="RoleManager测试" %>







角色名:



onClick="btnSubmit_Click" />






SortExpression="RoleName" />


SelectMethod="GetRoles" TypeName="Role">






备注:

用户和角色之间的操作如下

Roles.AddUserToRole - 向角色添加用户

Roles.RemoveUserFromRole - 从角色删除用户

Roles.GetRolesForUser - 用户所属的角色列表



Security/Role.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Security_Role : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}


protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Roles.RoleExists(txtRolename.Text.Trim()))
{
lblMsg.Text = "该角色已存在";
}
else
{
Roles.CreateRole(txtRolename.Text.Trim());
GridView1.DataBind();
}
}
}



注:需要用aspnet_regsql配置数据库


[源码下载]


作者:webabcd







添加到del.icio.us 添加到新浪ViVi 添加到百度搜藏 添加到POCO网摘 添加到天天网摘365Key 添加到和讯网摘 添加到天极网摘 添加到黑米书签 添加到QQ书签 添加到雅虎收藏 添加到奇客发现 diigo it 添加到饭否 添加到飞豆订阅 添加到抓虾收藏 添加到鲜果订阅 digg it 貼到funP 添加到有道阅读 Live Favorites 添加到Newsvine 打印本页 用Email发送本页 在Facebook上分享


Disclaimer Privacy Policy About us Site Map

If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.