.NET 7.0 - Create Custom AuthorizeAttribute and AllowAnonymous Attribute
Tutorial built with .NET 7.0
This is a super quick post on how to create custom [Authorize] and [AllowAnonymous] attributes in .NET 7.0.
The code snippets below are from a .NET 7.0 custom auth tutorial I posted recently that supports login with Facebook, the full tutorial and project code are available at .NET 7.0 - Facebook Authentication API Tutorial with Example.
Custom Authorize Attribute
The custom authorize attribute is created by extending the System.Attribute
class and implementing the Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
interface.
The OnAuthorization()
method is defined in the IAuthorizationFilter
interface, and is called to confirm the request is authorized. On successful authorization no action is taken and the request is passed through to the controller action method, if authorization fails a 401 Unauthorized
response is returned by setting the context.Result
property.
You can decorate a controller class and/or action method with the custom [Authorize]
attribute. When a controller class is decorated with [Authorize]
it applies to all action methods in that class, except for methods decorated with the custom [AllowAnonymous]
attribute.
In this example a request is authorized when there is an authenticated account attached to the current request (context.HttpContext.Items["Account"]
), but you can use any custom authorization code you like here according to your requirements.
namespace WebApi.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using WebApi.Entities;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
// skip authorization if action is decorated with [AllowAnonymous] attribute
var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
if (allowAnonymous)
return;
// authorization
var account = (Account?)context.HttpContext.Items["Account"];
if (account == null)
{
// not logged in or role not authorized
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
}
}
}
Custom Allow Anonymous Attribute
The custom [AllowAnonymous]
attribute is used to allow anonymous access to specified action methods of controllers that are decorated with the [Authorize]
attribute. The class is empty and simply used as a marker for the custom authorize attribute, which skips authorization if the action method is decorated with [AllowAnonymous]
.
The reason I created a custom AllowAnonymous
attribute instead of using the one in the .NET Core framework (Microsoft.AspNetCore.Authorization
) was for consistency with the other custom auth classes in the project and to avoid ambiguous reference errors between the custom and built-in namespaces.
namespace WebApi.Authorization;
[AttributeUsage(AttributeTargets.Method)]
public class AllowAnonymousAttribute : Attribute
{ }
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Follow me on Twitter at https://twitter.com/jason_watmore
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some .NET Help?
Search fiverr to find help quickly from experienced .NET developers.