ASP.NET froms 身份验证之Roles
roles和user都属于forms验证的配置参数,用法也类似,user是针对单个用户,roles是针对一组用户
要使用roles要在web.config的<system.web>中加入<roleManager enabled="true">以启用验证
在Global.asax要初始化Roles(如果之前没有初始化值)
void Application_Start(object sender, EventArgs e) { if(!Roles.RoleExists("admin")) Roles.CreateRole("admin"); if (!Roles.RoleExists("member")) Roles.CreateRole("member"); }
授权方式核心代码
string user = "userName"; string roleName = DropDownList1.SelectedValue; if (!Roles.IsUserInRole(user, roleName)) Roles.AddUserToRole(user, roleName); //默认的第1种,超时时间是在web.cofig中forms设置的timeout,单位是分钟,生成的cookie和凭证超时时间一样 FormsAuthentication.RedirectFromLoginPage(user, true); //第二种,自定义cookie超时时间,但是即使cookie没超时凭证超时,还是需要重新登录 HttpCookie AuthCookie = FormsAuthentication.GetAuthCookie(user, false); AuthCookie.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(AuthCookie); Response.Redirect(FormsAuthentication.GetRedirectUrl(user, true)); //第3种,可以自定义凭证和cookie超时时间 var nowDate = DateTime.Now; var myTicket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddMinutes(60), false, "other data"); string encryptedTicket = FormsAuthentication.Encrypt(myTicket); //加密用户凭证 //把用户凭证存入Cookie HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); //authCookie.Expires = DateTime.Now.AddMinutes(60); //不设置时间即为会话cookie Response.Cookies.Add(authCookie); Response.Redirect(FormsAuthentication.GetRedirectUrl(user, true));
例子中使用了微软自带的Sql提供程序来提供roles验证
示例下载:https://files.cnblogs.com/FlyCat/Forms-RolesSample.zip
数据库连接字符串根据实际情况修改,建库脚本一起在里面