zoukankan      html  css  js  c++  java
  • 使用FormsAuthenticationTicket进行登陆验证

                    if (账号密码验证成功)
                    {
                        //登陆成功
    
                        Session["User"] = account;
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                        (1,
                         account.ID.ToString(),
                         DateTime.Now,
                         DateTime.Now.AddDays(1),
                         true,
                         "1,5,7",   //可以存储role
                         "/"
                        );
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                        cookie.HttpOnly = true;
                        HttpContext.Response.Cookies.Add(cookie);
    
                        return RedirectToAction("Index", "Admin");
                    }
    

      

    需要使用的Role验证的地方

    if (User.IsInRole("1"))
    {
       //用户拥有“1”角色权限
    }
    

      

    在需要,验证的Controller、Action上面添加注解属性,比如这个Action 只允许RoleID 为包含1或2或3的访问,而当前用户RoleID为(1、5、7)就是用户有权访问了。

    [Authorize(Roles="1,2,3")]
    public ActionResult Index() 
    {
       return View();   
    }
    

      

    需要配置web.config

    <authentication mode="Forms">
          <forms loginUrl="~/Login/Index" timeout="2880" />
    </authentication>
    <roleManager enabled="true" defaultProvider="CustomRoleProvid">
          <providers>
            <clear/>
            <add name="CustomRoleProvid" type="HotelShow.CustomRoleProvider"/>  <!--自定义获取Role的方法-->
          </providers>
    </roleManager>
    

     

    CustomRoleProvider类的需要继承RoleProvider,实现GetRolesForUser方法

    
    
            public override string[] GetRolesForUser(string username)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                string role = ticket.UserData;
                return role.Split(',');
            }
    

      

  • 相关阅读:
    springmvc
    POJ 3683 Priest John's Busiest Day
    POJ 3678 Katu Puzzle
    HDU 1815 Building roads
    CDOJ UESTC 1220 The Battle of Guandu
    HDU 3715 Go Deeper
    HDU 3622 Bomb Game
    POJ 3207 Ikki's Story IV
    POJ 3648 Wedding
    HDU 1814 Peaceful Commission
  • 原文地址:https://www.cnblogs.com/fireicesion/p/8945399.html
Copyright © 2011-2022 走看看