2013-03-12 140 views
1

我的任务是为我们的MVC 4.0项目创建一个自定义成员资源提供程序。自定义成员资格提供程序+自定义CodeAccessSecurityAttribute

根据一个属性([Authorize]?),它必须知道允许尝试的用户是否允许使用该方法。

目前我有这样的:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class TestAuthorize : CodeAccessSecurityAttribute 
{ 
    public TestAuthorize(SecurityAction action) 
     : base(action) 
    { 
    } 

    public override IPermission CreatePermission() 
    { 
     throw new NotImplementedException(); 
    } 
} 

当我添加 return new PrincipalPermission(null,null,true)我期待许可的情况下有效,并且用户可以访问方法。

当我添加 return new PrincipalPermission(null.null,false)我期望的权限是无效的,用户将被拒绝访问该方法。

但是,只有当我使用throw new SecurityException("You are denied access")时,它才会停止,这也会强制MVC应用程序停止,除非在客户端处理此异常(使用try catch)。

我们有可能在我们的MVC项目中处理这个异常吗?

为我们所希望的例子已经通过使用属性来完成:

[TestAuthorize(SecurityAction.Demand)] 
public List<string> GetList() 
{ 
    //if access, return new List(); 
    //if no access, return null; 
} 

回答

1

敢肯定你希望从AuthorizeAttribute继承这里,不CodeAccessSecurityAttribute。在属性中,您覆盖AuthorizeCore,如果允许用户继续,则只需返回true;如果他们未被授权执行该方法的任何操作,则返回false。一个false结果将触发一个HTTP-401 Unauthorised响应,ASP.NET将通过将用户重定向到登录页面自动处理,以便他们可以作为具有正确访问权限的用户登录,但如果愿意,您可以更改此行为。

事实上,你甚至可能不需要创建自己的属性;如果您使用的是现有的ASP.NET MVC记忆体提供程序,或者您可以使用任何方法来使用它,那么现有的AuthorizeAttribute将适用于您。

+1

我试过这个; Nomather它返回true的真假..它仍然让人们访问该方法。 – 2013-03-13 08:06:42

+0

在另一个问题中,我被告知授权属性不是我想要的,因为我提供的是web服务而不是网站。当给定的方法/控制器/对象有一个httpcontext时,Authorize属性才起作用 – 2013-03-13 15:25:41

相关问题