1

After have tried this exact thing with REST and Controllers (all working) I would like to use GraphQL instead. The ScopeHandler doesn't seem to be called at all (it did in REST).

I don't really know where I should put my [Authorize] annotation. In REST I put it on the Controller class or on individual methods. I would like to do something similar and put it in my QueryType somehow. Is that possible? Or how should I go about doing this?

This is my code in Startup:

var domain = Environment.GetEnvironmentVariable("AUTH0_DOMAIN");
services.AddAuthentication( JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = domain;
        options.Audience = Environment.GetEnvironmentVariable("AUTH0:AUDIENCE");
    });

services.AddHttpContextAccessor();

services.AddGraphQLServer()
    .AddQueryType<Query>()
    .AddAuthorization();

services.AddAuthorization(options =>
{
    options.AddPolicy("admin", policy => 
    {
        policy.Requirements.Add(new HasScopeRequirement("read:beer", domain));
    });
});

services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();

And in configure. It looks like this:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseGraphQLPlayground(new GraphQLPlaygroundOptions
{
    Path = "/playground"
});

app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});

HasScopeHandler looks like this:

public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
    {
            context.Succeed(requirement);
            return Task.CompletedTask;
    }
}

This is the query i added as type in GraphQl

public class Query
{
    [Authorize(Policy = "admin")]
    public Domain.Beer GetBeer()
    {
        return new Domain.Beer(Guid.NewGuid().ToString(), "Test", "Test", 5.0, "IPA");
    }
}
Kryptor
  • 53
  • 5
  • Are you using the AuthorizeAttribute from Hot Chocolate or the one from ASP.NET Core? Normally this setup should work correctly, when using the AuthorizeAttribute of Hot Chocolate. – Tobias Tengler Sep 18 '21 at 06:16
  • @TobiasTengler I'm using the one from Hot Chocolate. So I get a 403 forbidden. – Kryptor Sep 18 '21 at 11:26

0 Answers0