Published: January 19 2023

.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
{ }

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by