ASP.NET MVC 2 Authorize - 自定义Authorize的实现
本文主要是转载的,通过这个小例子可以轻松自定义你的Authorize权限控制,因为我不是特别了解ASP.NET WebForm的MemberShip的实现机制,也不敢说自定义的性能是否过关,目前使用自定义的比较顺手。
在ASP.NET MVC2中使用自定义的AuthorizeAttribute绕过内置的Membership/Role机制
感谢 DSO at http://stackoverflow.com/users/38087/DSO
在ASP.NET MVC2中,我们可以使用Authorize Filter限制用户对内容的访问,如
- [Authorize]
- public class MyController : Controller
- {
- // ...
- }
- // 或者
- [Authorize(Roles="Admin")]
- public class MyController : Controller
- {
- // ...
- }
但前提是要用到Membership / Role机制。 我们要不就使用内置的机制,要不就派生出自己的。
不管怎样,都比较麻烦,其实我们可以绕过这套机制,而且还能使用AuthorizeAttribute。
以下是DSO的看法:
With MVC it is simple to bypass the Membership and Role provider framework altogether. Sometimes it is easier to do this than to implement custom Membership/Role providers, in particular if your authn/authz model doesn't quite fit the mold of those providers.
First, you should realize that you don't need to write everything from scratch, you can use the core Forms authentication API, which can be used independently of the Membership/Role provider framework:
- FormsAuthentication.SetAuthCookie- Call this after user has been authenticated, specify the user name
- Request.IsAuthenticated- Returns true if SetAuthCookie was called
- HttpContext.Current.User.Identity.Name- Returns the user name specified in the call to SetAuthCookie
So here is what you do in MVC to bypass the Membership/Role provider:
Authentication : In your controller, authenticate the user using your custom logic.If successful, callFormsAuthentication.SetAuthCookiewith the user name.
Authorization : Create a custom authorize attribute (deriving from AuthorizeAttribute) . In theAuthorizeCoreoverride, implement your custom authorization logic, taking the user inHttpContext.Current.User.Identity.Nameand the roles defined in the Roles property of the AuthorizeAttribute base class. Note you can also define properties on your custom authorization attribute and use that in your authorization logic. For example you can define a property representing roles as enumerated values specific to your app, instead of using the Roles property which is just a string.
Affix your controllers and actions with your custom authorize attribute, instead of the default Authorize attribute.
我看了感觉很受启发,但却不太清楚如何重载AuthorizeAttribute的AuthorizeCore方法。为此我做了个Demo:
1. 使用VS2010建立一个ASP.NET MVC2 Web工程Aut,在Model目录下新建一个MyAuthAttribute类,如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace AuthTest.Models
- {
- public class MyAuthAttribute : AuthorizeAttribute
- {
- // 只需重载此方法,模拟自定义的角色授权机制
- protected override bool AuthorizeCore(HttpContextBase httpContext)
- {
- string currentRole = GetRole(httpContext.User.Identity.Name);
- 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";
- }
- }
- }
- }
2. 修改HomeController, 如下
- 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);
- return View();
- }
- // 验证我们自定义的AuthorizeAttribute是否起作用,
- // 此Action只能由角色为“God”的用户访问
- [MyAuth(Roles="God")]
- public ActionResult About()
- {
- return View();
- }
- }
- }
3. 按F5调试,再点击页面上的“关于”链接,哈哈,知道了吧?