authorization icon indicating copy to clipboard operation
authorization copied to clipboard

A toolset for authorizing access to graph types for GraphQL .NET.

GraphQL Authorization

Join the chat at https://gitter.im/graphql-dotnet/graphql-dotnet

Run code tests Build artifacts Publish release CodeQL analysis

codecov Total alerts Language grade: C#

Activity Activity Activity

Size

A toolset for authorizing access to graph types for GraphQL.NET.

Provides the following packages:

Package Downloads NuGet Latest
GraphQL.Authorization Nuget Nuget

You can get all preview versions from GitHub Packages. Note that GitHub requires authentication to consume the feed. See here.

Usage

  • Register the authorization classes in your DI container - IAuthorizationEvaluator, AuthorizationSettings, and the AuthorizationValidationRule.
  • Provide a custom UserContext class that implements IProvideClaimsPrincipal.
  • Add policies to the AuthorizationSettings.
  • Apply a policy to a GraphType or Field (both implement IProvideMetadata):
    • using AuthorizeWith(string policy) extension method
    • or with GraphQLAuthorize attribute if using Schema + Handler syntax.
  • The AuthorizationValidationRule will run and verify the policies based on the registered policies.
  • You can write your own IAuthorizationRequirement.

Examples

  1. Fully functional basic Console sample.

  2. Fully functional ASP.NET Core sample.

  3. GraphType first syntax - use AuthorizeWith extension method on IGraphType or IFieldType.

public class MyType : ObjectGraphType
{
    public MyType()
    {
        this.AuthorizeWith("AdminPolicy");
        Field<StringGraphType>("name").AuthorizeWith("SomePolicy");
    }
}
  1. Schema first syntax - use GraphQLAuthorize attribute on type, method or property.
[GraphQLAuthorize("MyPolicy")]
public class MutationType
{
    [GraphQLAuthorize("AnotherPolicy")]
    public async Task<string> CreateSomething(MyInput input)
    {
        return await SomeMethodAsync(input);
    }

    [GraphQLAuthorize("SuperPolicy")]
    public string SomeProperty => Guid.NewGuid().ToString();
}

Known Issues

  • It is currently not possible to add a policy to Input objects using Schema first approach.