nicolae-lupei / GraphQL.Authorization.AspNetCore.Identity

GraphQL extensions for authorization through IdentityRoles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GraphQL.Authorization.AspNetCore.Identity

Build Status

.NET

NuGet Nuget

GraphQL extensions for authorization through IdentityRoles

Examples

Requirements:

        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
                    };
                });

        }
  1. Fully functional web demo.
  2. GraphType syntax - use AuthorizeWith.
public class DemoGraphType : ObjectGraphType<object>
{
    this.AuthorizeWith(GraphQLPolicy.Authorized);
    public DemoGraphType()
    {
        Field<IntGraphType>("id");
        Field<StringGraphType>("name")
            .AuthorizeWith(GraphQLPolicy.Authorized);
    }
}
  1. GraphType syntax - use RequireRoles
public class DemoGraphType : ObjectGraphType<object>
{
    public DemoGraphType()
    {
        Field<IntGraphType>("id");
        Field<StringGraphType>("name")
            .RequireRoles("Admin");
    }
}

About

GraphQL extensions for authorization through IdentityRoles

License:MIT License


Languages

Language:C# 100.0%