在ASP.NET MVC2中使用自定义的AuthorizeAttribute绕过内置的Membership/Role机制

本文介绍了如何在ASP.NET MVC2中绕过内置的Membership/Role机制,通过创建自定义的AuthorizeAttribute实现用户认证和授权。通过重载AuthorizeCore方法并结合Forms Authentication API,可以实现根据特定业务逻辑进行权限控制。示例代码展示了如何创建自定义授权属性并应用于控制器的Action上。
摘要由CSDN通过智能技术生成

// 所有原创文章转载请注明作者及链接
//
blackboycpp(AT)gmail.com
// QQ群: 135202158

 

 

感谢 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 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:

  1. Authentication : In your controller, authenticate the user using your custom logic.If successful, call FormsAuthentication.SetAuthCookie with the user name.

  2. Authorization : Create a custom authorize attribute (deriving from AuthorizeAttribute) . In the AuthorizeCore override, implement your custom authorization logic, taking the user in HttpContext.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.

  3. 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调试,再点击页面上的“关于”链接,哈哈,知道了吧?

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值