I am having trouble trying to use the standard Authorize attribute. It seems to be just ignored. My attempt to get around the problem was to write my own, which is being called but the parameters is not being passed.
The default constructor for BasicAuthorizeAttribute gets called but the one that takes the string parameter is never called. OnAuthorization is called too, but the Roles property is never set.
We are using Windows Authentication although the Authentication is set to None in the web.config. Changing this to Windows made no difference.
We are using MVC 5 and Castle Windsor, which I suspect is causing my problems.
On the controller as well as the action I have:
[BasicAuthorize(Roles = "Developer")]
The attribute filter
[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();
}
}
}
The Castle Windsor is set up as follows.
...
Component.For<FilterAttribute>().ImplementedBy<BasicAuthorizeAttribute>().LifeStyle.PerWebRequest.Named(typeof(BasicAuthorizeAttribute).FullName)
...
In the web.config we have the following
...
<authentication mode="None" />
...
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
...
I spent over a day on this and Google is not my friend any more. Anyone with advice on how to resolve this? Or preferably use the default [Authorize(Roles = "...")]
attribute?
EDIT
I found the culprit. The following lines was causing the problems.
var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
FilterProviders.Providers.Remove(oldProvider);
I found the culprit. The following lines was causing the problems.
var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
FilterProviders.Providers.Remove(oldProvider);