AllowAnonymous not working with Custom AuthorizationAttribute

allowanonymous web api
authorize(roles not working)
mvc custom authorize attribute not working
challengeasync
config filters add new authorizeattribute not working
authorization filter not working
authorizeattribute could not be found
asp net core custom authorization filter example

This has had me stumped for a while. None of the commonly encountered similar situations seem to apply here apparently. I've probably missed something obvious but I can't see it.

In my Mvc Web Application I use the Authorize and AllowAnonymous attributes in such a way that you have to explicitly open up an action as publicly available rather than lock down the secure areas of the site. I much prefer that approach. I cannot get the same behaviour in my WebAPI however.

I have written a custom Authorization Attribute that inherits from System.Web.Http.AuthorizeAttribute with the following:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizationAttribute : System.Web.Http.AuthorizeAttribute

I have this registered as a filter:

    public static void RegisterHttpFilters(HttpFilterCollection filters)
    {
        filters.Add(new MyAuthorizationAttribute());
    }

This all works as expected, actions are no longer available without credentials. The problem is that now the following method will not allow the AllowAnonymous attribute to do it's thing:

[System.Web.Http.AllowAnonymous]
public class HomeController : ApiController
{
    [GET("/"), System.Web.Http.HttpGet]
    public Link[] Index()
    {
        return new Link[] 
        { 
            new SelfLink(Request.RequestUri.AbsoluteUri, "api-root"),
            new Link(LinkRelConstants.AuthorizationEndpoint, "OAuth/Authorize/", "authenticate"),
            new Link(LinkRelConstants.AuthorizationTokenEndpoint , "OAuth/Tokens/", "auth-token-endpoint")
        };
    }
}

The most common scenario seems to be getting the two Authorize / AllowAnonymous attributes mixed up. System.Web.Mvc is for web apps and System.Web.Http is for WebAPI (as I understand it anyway).

Both of the Attributes I'm using are from the same namespace - System.Web.Http. I assumed that this would just inherit the base functionality and allow me to inject the code I need in the OnAuthotize method.

According to the documentation the AllowAnonymous attribute works inside the OnAuthorize method which I call immediately:

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);

Any thought's would be really appreciated.

Has anyone encountered this problem before and found the root cause?

In the AuthorizeAttribute there is the following code:

private static bool SkipAuthorization(HttpActionContext actionContext)
{
    Contract.Assert(actionContext != null);

    return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
               || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
}

Include this method in your AuthorizeAttribute class then add the following to the top of your OnAuthorization method to skip authorization if any AllowAnonymous attributes are found:

if (SkipAuthorization(actionContext)) return;

Skip Authorization for AllowAnonymous Attribute in Custom , If you use custom Authorization, attribute in controller level and want to allow any action by decorating “AllowAnonymous “ , it will not work. AllowAnonymous not working with Custom AuthorizationAttribute (3) This has had me stumped for a while. None of the commonly encountered similar situations seem to apply here apparently. I've probably missed something obvious but I can't see it.

ASP.NET MVC 4:

bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                         || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

or

 private static bool SkipAuthorization(AuthorizationContext filterContext)
    {
        Contract.Assert(filterContext != null);

        return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()
               || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
    }

Soruce: http://weblogs.asp.net/jongalloway/asp-net-mvc-authentication-global-authentication-and-allow-anonymous

ASP.NET MVC 4 AllowAnonymous Attribute and Authorize Attribute, AllowAnonymous not working with Custom AuthorizationAttribute In my Mvc Web Application I use the Authorize and AllowAnonymous  Allowanonymous attribute does not work in asp.net mvc cause confusions for Authorize and AllowAnonymous, for not working with Custom AuthorizationAttribute. 0.

Using C#6.0 Create a static class that extends the ActionExecutingContext.

public static class AuthorizationContextExtensions {
    public static bool SkipAuthorization(this ActionExecutingContext filterContext) {    
         Contract.Assert(filterContext != null);
         return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()|| filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
    }
}

Now your override filterContext will be able to call the extension method, just make sure they are in the same namespace, or include the proper using statement.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustomAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.SkipAuthorization()) return;// CALL EXTENSION METHOD
         /*NOW DO YOUR LOGIC FOR NON ANON ACCESS*/
    }
}

Authorize attribute not working, NET MVC 4 includes an AllowAnonymous Attribute for specifying those Mvc with the Authorize Attribute because you will find an AuthorizeAttribute in System. AllowAnonymous Attribute in ASP.NET MVC 4. As mentioned, if you create a new ASP.NET MVC 4 Internet Project in Visual Studio 2010 or Visual Studio 11 and view the AccountController you will notice the generous use of the AllowAnonymous Attribute on various login and register controller actions. Here are a few of those controller actions.

I must be using a different version of the .net framework or web api but hopefully this helps someone:

        bool skipAuthorization = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
        if (skipAuthorization)
        {
            return;
        }

Does AllowAnonymous override AuthorizeAttribute, I rebuilt the application but unfortunately it still is not working. In my web application I have the AuthorizeAttribute in my FilterConfig.cs file, like I mentioned earlier: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) ApplicationCookie); // Add custom user claims here return  Here Mudassar Ahmed Khan has explained with an example, how to implement and use the Authorize and AllowAnonymous Data Annotation attributes with Forms Authentication in ASP.Net MVC Razor. TAGs: ASP.Net, Entity Framework, MVC, Data Annotation, Forms Authentication

public class MyAuthorizationAuthorize : AuthorizeAttribute, IAuthorizationFilter
{
public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                    filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

                if (skipAuthorization) return;

            }
            else filterContext.Result = new HttpUnauthorizedResult();
        }
}

Simple authorization in ASP.NET Core, Remove the [AllowAnonymous] attribute and use your custom authorize along with an authorize attribute will result in the authorization code not running at all. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Sign up AllowAnonymous is ignored since migrating to ASP.NET Core 2.0 #1488

Custom Authorization filter in MVC, Authorization in MVC is controlled through the AuthorizeAttribute attribute You can also use the AllowAnonymous attribute to allow access by  Be aware that this code has counter-intuitive behavior: an [AllowAnonymous] attribute on the controller will override any authorization attributes on the method. To prevent this, you can add another custom attribute check for the ActionDescriptor against IAuthorizationFilter (or whatever base class/interface you're using) and only skip authentication if that is false when the anonymous controller is true.

AllowAnonymous is ignored since migrating to ASP.NET Core 2.0 , You need to use customize the Authorization Attribute instead. NET MVC · Working with Multiple tables in MVC Roles VARCHAR(100) NOT NULL, Add the AccessDenied action method with AllowAnonymous attribute as shown below​. One way to control access in your Razor Pages app is to use authorization conventions at startup. These conventions allow you to authorize users and allow anonymous users to access individual pages or folders of pages. The conventions described in this topic automatically apply authorization filters to control access.

Custom Authorization Filter In MVC With An Example, I am however using a custom security handler so it's possible this is the issue. GitHub is home to over 50 million developers working together to host and to call AddAuthorization on the MvcBuilder not service collection. Use of AllowAnonymous Attribute in ASP.Net MVC ? Rajender G May 9, 2017 Use of AllowAnonymous Attribute in ASP.Net MVC ? 2017-10-19T08:25:12+00:00 Interview Tips , MVC 1 Comment AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to

Comments
  • Make sure you use System.Web.Mvc.AllowAnonymousAttribute and not System.Web.Http.AllowAnonymousAttribute. It happens to me and I realised it three hours later...
  • found the same problem when I added a custom AuthorizationFilterAttribute and this solved it.
  • Be aware that this code has counter-intuitive behavior: an [AllowAnonymous] attribute on the controller will override any authorization attributes on the method. To prevent this, you can add another custom attribute check for the ActionDescriptor against IAuthorizationFilter (or whatever base class/interface you're using) and only skip authentication if that is false when the anonymous controller is true.
  • True, but I'd argue that is a bit of a design issue as well. If you are mixing secure and non-secure actions on the same controller it's time to move things around.
  • User asked for web api behavior, not mvc.
  • @LeandroTupone: When you use AllowAnonymousAttribute in the code rather than referencing the System.Web.Mvc, use System.Web.Http; then it should be fine.
  • I came here hoping I could adapt posters issue to the same issue I am having in MVC. Leaving satisfied thanks to this answer.