graphql-platform icon indicating copy to clipboard operation
graphql-platform copied to clipboard

Custom authorization attribute for Hotchocolate.Authorization

Open andreamorello93 opened this issue 1 year ago • 0 comments

Product

Hot Chocolate

Is your feature request related to a problem?

Policies in some cases are not handy as custom attributes with parameters such as [AuthorizeAge(22)] on Queries or Mutation

The solution you'd like

Make it possibile to write custom authorize attributes like microsoft Authorization

public class AuthorizeAgeAttribute : TypeFilterAttribute
{
    public AuthorizeAgeAttribute(int age) : base(typeof(AuthorizeAge))
    {
        Arguments = new object[] { age };
    }
}
public class AuthorizeAge : IAuthorizationFilter
{
    private readonly int _age;
    private readonly IUserService _userService;

    public AuthorizeMacroAndMicro(int age, IUserService userService)
    {
        _age = age;
        _userService = userService;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (_userService.Age < _age)
            context.Result = new ForbidResult();
    }
}

And being able to use it in mutation or queries like:

 [ExtendObjectType("Query")]
 public class HorrorFilmsQueryResolver
 {
     public HorrorFilmsQueryResolver() { }

     [GraphQLName("HorrorFilms")]
     [AuthorizeAge(18)]
     public Task<IEnumerable<Film>> Get([Service] IHorrorFilmsService filmService) => filmService.GetAll();

 }

andreamorello93 avatar Jan 13 '24 10:01 andreamorello93