GraphQL extensions for authorization through IdentityRoles
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization();
services.AddGraphQL(x =>
{
x.EnableMetrics = true;
})
.AddErrorInfoProvider(opt => opt.ExposeExceptionStackTrace = true)
.AddGraphTypes(ServiceLifetime.Scoped)
.AddDataLoader()
.AddSystemTextJson()
.AddGraphQLAuthorization()
.AddUserContextBuilder(ctx =>
{
var principalProvider = ctx.RequestServices.GetRequiredService<IHttpContextAccessor>();
var principal = principalProvider?.HttpContext?.User;
return new GraphQLUserContext
{
User = principal
};
});
}
- Fully functional web demo.
- GraphType syntax - use
AuthorizeWith
.
public class DemoGraphType : ObjectGraphType<object>
{
this.AuthorizeWith(GraphQLPolicy.Authorized);
public DemoGraphType()
{
Field<IntGraphType>("id");
Field<StringGraphType>("name")
.AuthorizeWith(GraphQLPolicy.Authorized);
}
}
- GraphType syntax - use
RequireRoles
public class DemoGraphType : ObjectGraphType<object>
{
public DemoGraphType()
{
Field<IntGraphType>("id");
Field<StringGraphType>("name")
.RequireRoles("Admin");
}
}