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?
[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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With