ASP.NET MVC权限管理

  ASP.NET MVC提供了AuthorizeAttribute,可用来控制Controller Action的安全性,但由于该属性所指定的角色或用户是写在代码中而不是在配置文件中的,因而不够灵活。

  为能够更灵活、更细粒度地控制权限,需要某种方法能够在配置文件(如web.config)中定义权限,这样才能在不需要重新编译代码的情况下,通过修改配置文件即可改变应用程序的授权。一个简单的场景,[CustomAuthorize(Roles = "Manager")] ,与系统自带的[Authorize(Roles = "Manager")] ,区别在于:后面的权限控制是通过Membership Provider完成的,即当前用户有没有权限是通过Context.User.IsInRole("Managers")来判断的;第一个则是自定义ActionFilter通过读取配置项来完成权限控制的。

   废话不说,上代码:

1. 从系统自带的AuthorizeAttribute继承(请注意:AuthorizeAttribute本身是从FilterAttribute继承且实现IAuthorizationFilter接口):

public class CustomAuthorizeAttribute : AuthorizeAttribute {
......
}

 

 

2. override其中关键的一个方法:AuthorizeCore

1 protected override bool AuthorizeCore(HttpContextBase httpContext) {
2 ...
3 }
4  
5 private static bool UserInRole(string role) {
6    if (user.IsInRole(role))
7         return true;
8     return false
9 

 

 

 

3. 实现自定义授权: 

protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null){  
    
throw new ArgumentNullException("httpContext");  
}
 
IPrincipal user 
= httpContext.User;
 
if (!user.Identity.IsAuthenticated) {
    
return false;
}
 
var rolesInSetting 
= ConfigurationManager.AppSettings["RolesFor:" + Roles]; 
var usersInSetting = ConfigurationManager.AppSettings["UsersFor:" + Users];

 

if (!String.IsNullOrEmpty(usersInSetting)) {
    
var users = usersInSetting.Split(newchar[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

  if (users != null|| users.Length > 0 && users.Contains(User.Identity.Name, StringComparer.OrdinalIgnoreCase))

    return true; 

 

if (String.IsNullOrEmpty(rolesInSetting))
    
returnfalsevar roles = rolesInSetting.Split(newchar[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
if (roles ==null|| roles.Length <=0)
    
returnfalse;

if (roles.Any(t => UserInRole(t))  
    
returntrue;

returnfalse}

 

 

4. 配置文件 web.config

<add key="RolesFor:Manager" value="admins, managers"/>

<add key="UsersFor:Manager" value="hackee,bill"/>

 

 

5. 配置Action方法:

 

[CustomAuthorize(Manager)]
public ActionResult GetSecureData() { ... } 

 

 

 

 

   

posted @ 2010-10-28 22:11  hackee  阅读(2832)  评论(2编辑  收藏  举报