-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Program.cs
47 lines (40 loc) · 1.52 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.Security.Claims;
using GraphQL;
using GraphQL.SystemTextJson;
using GraphQL.Types;
using GraphQL.Validation;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection().AddGraphQL(builder => builder
.AddAuthorization(settings => settings.AddPolicy("AdminPolicy", p => p.RequireClaim("role", "Admin"))));
using var serviceProvider = services.BuildServiceProvider();
const string definitions = """
type User {
id: ID
name: String
}
type Query {
viewer: User
users: [User]
}
""";
var schema = Schema.For(definitions, builder => builder.Types.Include<Query>());
// Claims principal must look something like this to allow access.
// GraphQLUserContext.User alternates below for demonstration purposes.
int counter = 0;
var authorizedUser = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("role", "Admin") }));
var nonAuthorizedUser = new ClaimsPrincipal(new ClaimsIdentity());
while (true)
{
string json = await schema.ExecuteAsync(options =>
{
options.Query = "{ viewer { id name } }";
options.Root = new Query();
options.ValidationRules = DocumentValidator.CoreRules.Concat(serviceProvider.GetServices<IValidationRule>());
options.RequestServices = serviceProvider;
options.User = counter++ % 2 == 0 ? authorizedUser : nonAuthorizedUser;
}).ConfigureAwait(false);
Console.WriteLine(json);
Console.WriteLine();
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}