Page.User.IsInRole()使用Form认证

1.web.config里加

<authentication mode="Forms">
  <forms
  name=".ASPXAUTH"
  loginUrl="Login.aspx"
  defaultUrl="default.aspx"
  protection="All"
  timeout="30"
  path="/">
  </forms>
</authentication>
<authorization>
  <deny users="?"/>
</authorization>

2,Login.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
<script runat="server">

  protected void Button1_Click(object sender, EventArgs e)
  {
    String username = UserName.Text;

      if (username.EndsWith("mxh", StringComparison.InvariantCultureIgnoreCase) && Password.Text.EndsWith("mxh", StringComparison.InvariantCultureIgnoreCase))
      {

//下面代码主要是把认证信息写到Cookie里,方便后面的读取
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(30),
        false,
        "admin|reader|editor",
        FormsAuthentication.FormsCookiePath);
        string encTicket = FormsAuthentication.Encrypt(ticket);
        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
        Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));

 

 

//            FormsAuthentication.SetAuthCookie(tbx_username.Text.TrimEnd(), true, FormsAuthentication.FormsCookiePath);

//其中加粗体为主要语句,有此一句就可以实现HttpContext.Current.User.Identity.IsAuthenticated=true;


//            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
//1, tbx_username.Text, DateTime.Now, DateTime.Now.AddMinutes(20), false, tbx_username.Text);
//            // generate new identity
//            FormsIdentity identity = new FormsIdentity(ticket);
//            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
//            // write to client.
//            Response.Cookies.Add(cookie);

 


      }
      else
      {
        Response.Write("密码不正确");
      }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  用户名:<asp:TextBox ID="UserName" runat="server" />mxh <br />
  密码:<asp:TextBox ID="Password" TextMode="password" runat="server" />mxh<br />
  <asp:Button ID="Button1" Text="登录" runat="server" onclick="Button1_Click" />
  </form>
</body>
</html>



3,Global.asax

<%@ Application Language="C#" %>
<script runat="server">
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
      string cookieName = FormsAuthentication.FormsCookieName;

      HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
      //HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
      if (null == authCookie)
      {
        // 没有身份验证 cookie。
        return;
      }
      FormsAuthenticationTicket authTicket = null;
      authTicket = FormsAuthentication.Decrypt(authCookie.Value);

      if (null == authTicket)
      {
        // 无法解密 Cookie。
        return;
      }

//重要的是从Cookie里取出当前用户所属的角色信息

      string[] roles = authTicket.UserData.Split(new char[] { '|' });
      FormsIdentity id = new FormsIdentity(authTicket);
      System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
      Context.User = principal;
    }

</script>

==========================

protected void Application_AuthorizeRequest(object sender, System.EventArgs e)
{
    HttpApplication App = (HttpApplication) sender;

    //获取本次Http请求相关的HttpContext对象
     HttpContext Ctx = App.Context ;

    //验证过的用户才进行role的处理
    if (Ctx.Request.IsAuthenticated == true)
    {
        FormsIdentity Id = (FormsIdentity)Ctx.User.Identity ;
        //取得身份验证票
        FormsAuthenticationTicket Ticket = Id.Ticket ;

         //将身份验证票中的role数据转成字符串数组
        string[] Roles = Ticket.UserData.Split (',') ;

       //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息     
        Ctx.User = new GenericPrincipal (Id, Roles) ;  
   }
}

这段代码和上面是等效的。

解释:

.NET提供了一个通用的RBS抽象,主体(principal)封装了标识(identity)和该标识所属的角色(role)。因此.NET runtime把基于角色的认证建立在主体( principal)作为主要参考点上。

==========================

4,使用
 protected void Page_Load(object sender, EventArgs e)
 {
   Response.Write(Page.User.IsInRole("reader"));
}


用户验证和角色分配完全可以从数据库读取。

出处:http://www.cnblogs.com/xiaoliepower/articles/1802381.html

你可能感兴趣的:(form)