ASP.NET常用身份验证:windows 和Forms。window常用于同一个域的用户,比喻公司内部网站。Forms是一种基于Cookie的认证方式。由于Forms 的认证方式更普遍。以下是自己定制Forms认证的方式:
一:修改配置文件:设置认证方式。
<authentication mode="Forms">
<forms name="test" loginUrl="Default.aspx" defaultUrl="index.aspx" protection="All"></forms>
</authentication>
二:设置网站文件的角色权限。例如:只有admin能访问admin目录下的文件
<location path="admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
三:设置自定义的角色提供者。
<roleManager defaultProvider="MyRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add name="MyRoleProvider"
type="MyRoleProvider"
writeExceptionsToEventLog="false" />
</providers >
</roleManager >
四:实现MyRoleProvider类。
public class MyRoleProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
FormsIdentity Id = HttpContext.Current.User.Identity as FormsIdentity;
if (Id != null)
{
return Id.Ticket.UserData.Split(new Char[] { ',' });
}
return null;
}
/******
实现RoleProvider的抽象方法。
******/
}
五:设置用户的票证。其中包含用户的角色信息。
if (/*用户合法的情况*/)
{
string userRole = "admin";//模拟角色
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,
TextBox1.Text,
DateTime.Now,
DateTime.Now.AddMinutes(1),
false,
userRole);//用户角色
string emTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, emTicket);
Response.Cookies.Add(UserCookie);
string[] user = new string[] { TextBox1.Text };
Context.Response.Redirect(FormsAuthentication.GetRedirectUrl(this.TextBox1.Text, false));
}