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

      

  • 相关阅读:
    经典语录一
    例子二
    例子一
    模板加载
    vim 程序编辑器
    文件与文件系统的压缩,打包与备份
    Linux 磁盘与文件系统管理
    文件与目录操作
    Linux 的文件/目录权限
    Linux 指令代码,热键以及文件放置安排
  • 原文地址:https://www.cnblogs.com/fireicesion/p/8945399.html
Copyright © 2020-2023  润新知