Forms 验证进行角色控制全攻略
原作:lzumcj
说明:曾经想做一个类似于 Windows 2000 / XP 等的可分组角色控制,找了诸多资料未过。后终于在 misrosoft 的网站找到一篇英文的相关资料,看过后付诸于实践,成功!总结与此,以享后人。
1。配置IIS,允许匿名访问。
2。配置 Asp.Net 的验证模式为 Forms 。
<!-- web.config -->
<authentication mode="Forms">
<forms name="MyAppFormsAuth"
loginUrl="login.aspx"
protection="Encryption"
timeout="20"
path="/" >
</forms>
</authentication>
3。创建登录页面,并验证提供的信任状(credentials)。
4。从自定义的数据存储中获得角色列表(role list)。
5。创建 Forms authentication ticket (store roles in the ticket)。
// This event handler executes when the user clicks the Logon button
// having supplied a set of credentials
private void Logon_Click(object sender, System.EventArgs e)
{
// Validate credentials against either a SQL Server database
// or Active Directory
bool isAuthenticated = true;
if (isAuthenticated == true )
{
// Retrieve the set of roles for this user from the SQL Server
// database or Active Directory. The roles are returned as a
// string that contains pipe separated role names
// for example "Manager|Employee|Sales|"
// This makes it easy to store them in the authentication ticket
//string roles = RetrieveRoles( txtUserName.Text, txtPassword.Text);
string roles = "admin";
// Create the authentication ticket and store the roles in the
// custom UserData property of the authentication ticket
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(
1, // version
txtUserName.Value, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(20),// Expiration
false, // Persistent
roles ); // User data
// Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
// Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
// Redirect the user to the originally requested page
Response.Redirect( FormsAuthentication.GetRedirectUrl(txtUserName.Value,false ));
}
}
6。创建 IPrincipal 对象。
7。Put the IPrincipal object into the current HTTP context.
<!-- Global.asax -->
<%@ Application language="C#" %>
<%@ import namespace="System.Security.Principal" %>
<script runat="server">
protected void Application_AuthenticateRequest(Object sender , EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned
// a pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[]{'|'});
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
</script>
8。基于用户名/角色成员资格批准用户。
IPrincipal.IsInRole