自定义成员资格提供程序+自定义CodeAccessSecurityAttribute

时间:2013-03-12 15:25:04

标签: c# security asp.net-mvc-4 attributes

我的任务是为我们的MVC 4.0项目的方法创建一个自定义成员提供程序。

根据属性([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 个答案:

答案 0 :(得分:1)

很确定你想在这里继承AuthorizeAttribute,而不是CodeAccessSecurityAttribute。在您的属性中,您覆盖AuthorizeCore,如果允许用户继续,则返回true,如果他们没有被授权执行该方法的操作,则只返回falsefalse结果将触发HTTP-401 Unauthorised响应,ASP.NET会自动将用户重定向到登录页面,以便他们可以作为具有正确访问权限的人员登录,但您可以更改此行为你希望。

实际上,您甚至可能不需要创建自己的属性;如果您正在使用现有的ASP.NET MVC mempership提供程序,或者您可以使用它来使用它,那么现有的AuthorizeAttribute将适合您。

相关问题