Sobes.tech
Junior — Middle

Have you had experience working with authorization filters in applications?

sobes.tech AI

Answer from AI

In C#, authorization filters are often used in ASP.NET Core to control access to application resources. They allow checking whether the user has the necessary rights before executing a controller action.

Example of a simple authorization filter:

public class CustomAuthorizationFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            context.Result = new UnauthorizedResult();
        }
        // Additional role or permission checks can be added here
    }
}

This filter can be applied to a controller or an action via an attribute:

[ServiceFilter(typeof(CustomAuthorizationFilter))]
public class MyController : Controller
{
    // Actions
}

Thus, authorization filters allow centralized access management and simplify security maintenance in the application.