Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether the allow anonymous is on or not in ASP.NET Core

I need a way to check if "allow anonymous" is on/off in the controller action. Whether it comes from controller attribute, action attribute

[AllowAnonymous]

or it is set as filter in the MvcOptions

opts.Filters.Add(new AllowAnonymousFilter());

Is it possible?

like image 205
moozywu Avatar asked Mar 04 '20 10:03

moozywu


People also ask

What is AllowAnonymous in ASP.NET Core?

[AllowAnonymous] bypasses all authorization statements. If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) is ignored.

What attributes will ensure anonymous users can access a specific controller action?

One of the new features in ASP.NET MVC 4 is the 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 certain controller actions, like the login and register Actions.


1 Answers

It seems you need to check whether a controller and action does contain AllowAnonymousAttribute from your custom authentication filter during a request. So you can do this as follows:

public class CustomAuthorizationFilter : IAsyncAuthorizationFilter
{
    public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException(nameof(filterContext));
        }

        bool hasAllowAnonymous = filterContext.ActionDescriptor.EndpointMetadata
                                 .Any(em => em.GetType() == typeof(AllowAnonymousAttribute)); //< -- Here it is

        if (hasAllowAnonymous) return;

        // Do your authorization check here
    }
}
like image 84
TanvirArjel Avatar answered Sep 30 '22 03:09

TanvirArjel