zoukankan      html  css  js  c++  java
  • AuthorizeAttribute示例

    using System;   
    using System.Collections.Generic;   
    using System.Linq;   
    using System.Web;   
    using System.Web.Mvc;   
    namespace AuthTest.Models   
    {   
        public class MyAuthAttribute : AuthorizeAttribute   
        {   
            // 只需重载此方法,模拟自定义的角色授权机制,推荐通过Idetity获取用户信息, 当然也可以通过Session获取,如果通过Session获取需要在验证的时候吧用户信息写入Session   
            protected override bool AuthorizeCore(HttpContextBase httpContext)   
            {   
                string currentRole = GetRole(httpContext.User.Identity.Name);   
                //string currentRole = GetRole(Session["user"].ToString()); 通过Session获取
                if(Roles.Contains(currentRole ) )   
                    return true;   
                return base.AuthorizeCore(httpContext);   
            }   
       
            // 返回用户对应的角色, 在实际中, 可以从SQL数据库中读取用户的角色信息   
            private string GetRole(string name)   
            {   
                switch(name)   
                {   
                    case "aaa":  return "User";   
                    case "bbb": return "Admin";   
                    case "ccc": return "God";   
                    default: return "Fool";   
                }   
            }   
        }   
       
    }
    using System;   
    using System.Collections.Generic;   
    using System.Linq;   
    using System.Web;   
    using System.Web.Mvc;   
    using System.Web.Security;   
    using AuthTest.Models;   
    namespace AuthTest.Controllers   
    {   
        [HandleError]   
        public class HomeController : Controller   
        {   
            public ActionResult Index()   
            {   
                ViewData["Message"] = "欢迎使用 ASP.NET MVC!";   
                // 模拟用户成功登录   
                FormsAuthentication.SetAuthCookie("aaa", false);  
                //Session["user"]="aaa" 把用户信息写入Session 
                return View();   
            }   
       
            // 验证我们自定义的AuthorizeAttribute是否起作用,    
             // 此Action只能由角色为“God”的用户访问   
            [MyAuth(Roles="God")]   
            public ActionResult About()   
            {   
                return View();   
            }   
        }   
    }
  • 相关阅读:
    python 通过*.cer *..pfx 获取公钥私钥
    python 交集 并集 差集
    python3 RSA加密、解密、签名
    Go 入门
    ansible入门篇一
    ACM/ICPC 之 两道dijkstra练习题(ZOJ1053(POJ1122)-ZOJ1053)
    数学软件 之 基于MATLAB的DFP算法
    ACM/ICPC 之 最短路径-dijkstra范例(ZOJ2750-POJ1135(ZOJ1298))
    ACM/ICPC 之 判别MST唯一性-Kruskal解法(POJ1679)
    ACM/ICPC 之 四道MST-Prim解法(POJ1258-POJ1751-POJ2349-POJ3026)
  • 原文地址:https://www.cnblogs.com/answercard/p/5061279.html
Copyright © 2011-2022 走看看