A toolset for authorizing access to graph types for GraphQL .NET.
- Register the authorization classes in your container (
IAuthorizationEvaluator
,AuthorizationSettings
, and theAuthorizationValidationRule
). - Provide a
UserContext
class that implementsIProvideClaimsPrincipal
. - Add policies to the
AuthorizationSettings
. - Apply a policy to a GraphType or Field (which implement
IProvideMetadata
) usingAuthorizeWith(string policy)
. - The
AuthorizationValidationRule
will run and verify the policies based on the registered policies. - You can write your own
IAuthorizationRequirement
. - Use
GraphQLAuthorize
attribute if using Schema + Handler syntax.
public static void AddGraphQLAuth(this IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IAuthorizationEvaluator, AuthorizationEvaluator>();
services.AddTransient<IValidationRule, AuthorizationValidationRule>();
services.TryAddSingleton(s =>
{
var authSettings = new AuthorizationSettings();
authSettings.AddPolicy("AdminPolicy", _ => _.RequireClaim("role", "Admin"));
return authSettings;
});
}
public static void UseGraphQLWithAuth(this IApplicationBuilder app)
{
var settings = new GraphQLSettings
{
BuildUserContext = ctx =>
{
var userContext = new GraphQLUserContext
{
User = ctx.User
};
return Task.FromResult(userContext);
}
};
var rules = app.ApplicationServices.GetServices<IValidationRule>();
settings.ValidationRules.AddRange(rules);
app.UseMiddleware<GraphQLMiddleware>(settings);
}
public class GraphQLUserContext : IProvideClaimsPrincipal
{
public ClaimsPrincipal User { get; set; }
}
public class GraphQLSettings
{
public Func<HttpContext, Task<object>> BuildUserContext { get; set; }
public object Root { get; set; }
public List<IValidationRule> ValidationRules { get; } = new List<IValidationRule>();
}
GraphType first syntax - use AuthorizeWith
.
public class MyType : ObjectGraphType
{
public MyType()
{
this.AuthorizeWith("AdminPolicy");
Field<StringGraphType>("name").AuthorizeWith("SomePolicy");
}
}
Schema first syntax - use GraphQLAuthorize
attribute.
[GraphQLAuthorize(Policy = "MyPolicy")]
public class MutationType
{
[GraphQLAuthorize(Policy = "AnotherPolicy")]
public async Task<string> CreateSomething(MyInput input)
{
return Guid.NewGuid().ToString();
}
}
- It is currently not possible to add a policy to Input objects using Schema first approach.