Search code examples
c#graphqlgraphql-dotnet

GraqhQL problem with auth on fields with JWT


So I have graphql as backend and React / Apollo as Frontend. I have already implemented my JWT Token Auth, which works fine.

Additional to that I have my Middleware, in which the HttpContext is given and the user is correctly loaded with all Claims:

namespace xxx.Web.GQL.Middleware
{
public class GraphQLMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IDocumentWriter _writer;
    private readonly IDocumentExecuter _executor;
    private readonly ISchema _schema;

    public GraphQLMiddleware(RequestDelegate next, IDocumentWriter writer, IDocumentExecuter executor, ISchema schema)
    {
        _next = next;
        _writer = writer;
        _executor = executor;
        _schema = schema;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        if (httpContext.Request.Path.StartsWithSegments("/graphql") && string.Equals(httpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
        {
            string body;
            using (var streamReader = new StreamReader(httpContext.Request.Body))
            {
                body = await streamReader.ReadToEndAsync();

                var request = JsonConvert.DeserializeObject<GraphQLQuery>(body);

                var result = await _executor.ExecuteAsync(doc =>
                {
                    doc.Schema = _schema;
                    doc.Query = request.Query;
                    doc.Inputs = request.Variables.ToInputs();
                    doc.ExposeExceptions = true;
                    doc.UserContext = httpContext.User;
                }).ConfigureAwait(false);

                var json = _writer.Write(result);
                await httpContext.Response.WriteAsync(json);
            }
        }
        else
        {
            await _next(httpContext);
        }
    }
}
}

Until here it works perfectly fine.

Sadly I am struggling with any further. I added the GraphQL.Authorization Nuget but all given information are not enough that I could build some working code with it.

What I could do is of course access the userContext within the resolver of a query and check it "by hand" but I try to avoid it ;)

Field<StringGraphType>(
          name: "hallo",
          resolve: c =>
          {
              var userPrinc = (ClaimsPrincipal)c.UserContext;
              var allowed = userPrinc.Claims.Any(x => x.Type == "Role" && x.Value == "Admin" || x.Value == "Mod");
              if (!allowed)
              {
                  throw new Exception("TODO: Make this a 401 FORBIDDEN");
              }
              return "World";
          }

So what I want is: Check the claims on Field-Level (for Query or Mutation) for a given Claim with one or more roles in it.


Solution

  • First one needs to define the policies. Do this in the ConfigureServices method. For example:

    services.AddGraphQLAuth(_ =>
    {
        _.AddPolicy("name-of-policy", p => p.RequireClaim("role", "admin"));
    });
    

    And make sure are adding the user context with the AddUserContextBuilder method, for example:

    services.AddGraphQL(options =>
    {
        options.ExposeExceptions = true;
    }).AddUserContextBuilder(context => new GraphQLUserContext { User = context.User });
    

    Finally you need to use the AuthorizeWith extension method that is part of GraphQL.Authorization on the field. For example:

    Field<StringGraphType>( /* snip */ )
        .AuthorizeWith("name-of-policy");
    

    Take a look at the example here: https://github.com/graphql-dotnet/authorization/tree/master/src/Harness