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(',');
            }
    

      

  • 相关阅读:
    IOS照相
    起学习iOS开发专用词汇
    django[post与get测试]
    起名字好难啊!(初识Django)
    MTV模型
    Django安装以及介绍
    数据库操作
    数据库其它操作
    数据库经典习题,
    数据库基本操作
  • 原文地址:https://www.cnblogs.com/fireicesion/p/8945399.html
Copyright © 2011-2022 走看看