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

本文关键字:自定义 CodeAccessSecurityAttribute 程序 成员 | 更新日期: 2023-09-27 18:03:44

我的任务是为我们的MVC 4.0项目的方法创建一个custommembership提供程序。

基于一个属性([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;
}  

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

很确定你想从AuthorizeAttribute继承,而不是CodeAccessSecurityAttribute。在您的属性中,您可以覆盖AuthorizeCore,如果应该允许用户继续,则返回true,如果未授权用户执行该方法所做的任何操作,则返回falsefalse结果将触发HTTP-401 Unauthorised响应。. NET通过将用户重定向到登录页面来自动处理,以便他们可以作为具有正确访问权限的人登录,尽管您可以根据需要更改此行为。

事实上,你甚至可能不需要创建你自己的属性;如果您使用的是现有的ASP。. NET MVC成员提供程序,或者你可以得到任何你正在使用它玩得很好,那么现有的AuthorizeAttribute将为你工作。