zoukankan      html  css  js  c++  java
  • ASP.NET froms 身份验证之Roles

    roles和user都属于forms验证的配置参数,用法也类似,user是针对单个用户,roles是针对一组用户

    要使用roles要在web.config的<system.web>中加入<roleManager enabled="true">以启用验证

    在Global.asax要初始化Roles(如果之前没有初始化值)

      void Application_Start(object sender, EventArgs e)
    {
               if(!Roles.RoleExists("admin"))
                   Roles.CreateRole("admin");
    
               if (!Roles.RoleExists("member"))
                   Roles.CreateRole("member");
    }

    授权方式核心代码

                string user = "userName";
    
                string roleName = DropDownList1.SelectedValue;
                if (!Roles.IsUserInRole(user, roleName))
                    Roles.AddUserToRole(user, roleName);
    
                //默认的第1种,超时时间是在web.cofig中forms设置的timeout,单位是分钟,生成的cookie和凭证超时时间一样
                FormsAuthentication.RedirectFromLoginPage(user, true);
    
                //第二种,自定义cookie超时时间,但是即使cookie没超时凭证超时,还是需要重新登录
                HttpCookie AuthCookie = FormsAuthentication.GetAuthCookie(user, false);
                AuthCookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(AuthCookie);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(user, true));
    
                //第3种,可以自定义凭证和cookie超时时间
                var nowDate = DateTime.Now;
                var myTicket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddMinutes(60), false, "other data");
                string encryptedTicket = FormsAuthentication.Encrypt(myTicket); //加密用户凭证
                //把用户凭证存入Cookie 
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                //authCookie.Expires = DateTime.Now.AddMinutes(60); //不设置时间即为会话cookie
                Response.Cookies.Add(authCookie);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(user, true));

    例子中使用了微软自带的Sql提供程序来提供roles验证

    示例下载:https://files.cnblogs.com/FlyCat/Forms-RolesSample.zip

    数据库连接字符串根据实际情况修改,建库脚本一起在里面

  • 相关阅读:
    GSM和GPRS的区别
    IP规划和VLSM子网划分例题
    20190806-sed面试题
    yum.rpm一点点
    实验:基于http的yum源
    vim编辑二进制文件
    关于find的-perm
    误删tree命令如何恢复
    删除Linux的依赖库并进入救援模式恢复
    第六天、用户、组、权限、grep
  • 原文地址:https://www.cnblogs.com/FlyCat/p/2624512.html
Copyright © 2011-2022 走看看