感谢 DSO at http://stackoverflow.com/users/38087/DSO
在ASP.NET MVC2中,我们可以使用Authorize Filter限制用户对内容的访问,如
但前提是要用到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 nameRequest.IsAuthenticated
- Returns true if SetAuthCookie was calledHttpContext.Current.User.Identity.Name
- Returns the user name specified in the call to SetAuthCookieSo 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.SetAuthCookie
with the user name.
Authorization : Create a custom authorize attribute (deriving from AuthorizeAttribute) . In theAuthorizeCore
override, implement your custom authorization logic, taking the user inHttpContext.Current.User.Identity.Name
and 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类,如下:
2. 修改HomeController, 如下
3. 按F5调试,再点击页面上的“关于”链接,哈哈,知道了吧?