asp.net forms身份验证,避免重复造轮子(2)


protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null) {
string[] roles = ticket.UserData.Split(',');
FormsIdentity id = new FormsIdentity(ticket);
System.Security.Principal.GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
}
}


step 6: 如何得到当前登录用户的信息

复制代码 代码如下:


public static TopicUser CurrentUser {
get {
DataService.TopicUser user = new DataService.TopicUser();
FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = identity.Ticket;
string userdata = ticket.UserData; //获取自定义的 UserData 串
if (!string.IsNullOrEmpty(userdata)) {
if (userdata.IndexOf(',') > 0 && userdata.IndexOf('|') > 0)
{
//roles , userid | userchname
string uinfo = userdata.Split(',')[1];
string[] u = uinfo.Split('|');
int uid = 0;
int.TryParse(u[0], out uid);
user.autoID = uid;
user.UserChName = u[1];
user.UserName = HttpContext.Current.User.Identity.Name;
}
}
return user;
}
}


由此得到当前登录用户的 ID 为 UserBase.CurrentUser.autoID ; 真实名字是: UserBase.CurrentUser.UserChName ;
判断当前用户的角色是否为管理员: HttpContext.Current.User.IsInRole("1") ; // 1 为管理员
退出当前登录的方法:
LogOut.aspx

复制代码 代码如下:


protected void Page_Load(object sender, EventArgs e)
{
System.Web.Security.FormsAuthentication.SignOut();
Response.Write("<script>window.top.location='login.aspx';</script>");
Response.End();
}


至此,身份验证完成。我们不用费尽心思在四处堆放用户是否登录判断的代码了。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjjspg.html