自定义授权过滤器未传入参数

时间:2015-08-27 10:09:25

标签: asp.net-mvc-5 castle-windsor custom-attributes

我无法尝试使用标准的Authorize属性。它似乎只是被忽略了。我试图解决这个问题的方法是编写我自己的,正在调用但参数没有被传递。

调用BasicAuthorizeAttribute的默认构造函数,但从不调用带有字符串参数的构造函数。也调用OnAuthorization,但永远不会设置Roles属性。

虽然在web.config中将身份验证设置为无,但我们正在使用Windows身份验证。将此更改为Windows没有任何区别。

我们正在使用MVC 5和Castle Windsor,我怀疑这会导致我的问题。

在控制器上以及我的操作:

[BasicAuthorize(Roles = "Developer")]

属性过滤器

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class BasicAuthorizeAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public string Roles { get; set; }

    public BasicAuthorizeAttribute()
    {
    }

    public BasicAuthorizeAttribute(string roles)
    {
        Roles = roles;
    }

    public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (!string.IsNullOrWhiteSpace(Roles))
        {
            // Check user roles here

            // User not in role
            filterContext.Result = new HttpUnauthorizedResult(); // mark unauthorized
        }
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        var user = filterContext.HttpContext.User;
        if (user == null || !user.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

温莎城堡的设置如下。

...
Component.For<FilterAttribute>().ImplementedBy<BasicAuthorizeAttribute>().LifeStyle.PerWebRequest.Named(typeof(BasicAuthorizeAttribute).FullName)
...

在web.config中我们有以下

...
<authentication mode="None" />
...
<modules>
        <remove name="FormsAuthenticationModule" />
</modules>
...

我在这上花了一天多时间,谷歌不再是我的朋友了。任何有关如何解决此问题的建议?或者最好使用默认的[Authorize(Roles = "...")]属性?

修改

我找到了罪魁祸首。以下几行导致了问题。

var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
FilterProviders.Providers.Remove(oldProvider);

1 个答案:

答案 0 :(得分:1)

我找到了罪魁祸首。以下几行导致了问题。

var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
FilterProviders.Providers.Remove(oldProvider);
相关问题