-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathAuthorizationHelper.cs
More file actions
59 lines (53 loc) · 2.22 KB
/
Copy pathAuthorizationHelper.cs
File metadata and controls
59 lines (53 loc) · 2.22 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
namespace GraphQL.Server.Transports.AspNetCore;
/// <summary>
/// Helper methods for performing connection authorization.
/// </summary>
public static class AuthorizationHelper
{
/// <summary>
/// Performs connection authorization according to the options set within
/// <see cref="AuthorizationParameters{TState}"/>. Returns <see langword="true"/>
/// if authorization was successful or not required.
/// </summary>
public static async ValueTask<bool> AuthorizeAsync<TState>(AuthorizationParameters<TState> options, TState state)
{
if (options.AuthorizationRequired)
{
if (!((options.HttpContext.User ?? NoUser()).Identity ?? NoIdentity()).IsAuthenticated)
{
if (options.OnNotAuthenticated != null)
await options.OnNotAuthenticated(state);
return false;
}
}
if (options.AuthorizedRoles?.Any() ?? false)
{
var user = options.HttpContext.User ?? NoUser();
foreach (var role in options.AuthorizedRoles!)
{
if (user.IsInRole(role))
goto PassRoleCheck;
}
if (options.OnNotAuthorizedRole != null)
await options.OnNotAuthorizedRole(state);
return false;
}
PassRoleCheck:
if (options.AuthorizedPolicy != null)
{
var authorizationService = options.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
var authResult = await authorizationService.AuthorizeAsync(options.HttpContext.User ?? NoUser(), null, options.AuthorizedPolicy);
if (!authResult.Succeeded)
{
if (options.OnNotAuthorizedPolicy != null)
await options.OnNotAuthorizedPolicy(state, authResult);
return false;
}
}
return true;
}
private static IIdentity NoIdentity()
=> throw new InvalidOperationException($"IIdentity could not be retrieved from HttpContext.User.Identity.");
private static ClaimsPrincipal NoUser()
=> throw new InvalidOperationException("ClaimsPrincipal could not be retrieved from HttpContext.User.");
}