Skip to content

Commit ed076b6

Browse files
committed
Updated AuthorizationValidationRule to skip authorization checks when the field is not included or skipped due to directives.
1 parent 0d59ebf commit ed076b6

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/GraphQL.Authorization/AuthorizationValidationRule.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
using System.Linq;
12
using System.Threading.Tasks;
3+
using GraphQL.Execution;
24
using GraphQL.Language.AST;
35
using GraphQL.Types;
46
using GraphQL.Validation;
@@ -49,7 +51,7 @@ public Task<INodeVisitor> ValidateAsync(ValidationContext context)
4951
{
5052
var fieldDef = context.TypeInfo.GetFieldDef();
5153

52-
if (fieldDef == null)
54+
if (fieldDef == null || SkipAuthCheck(fieldAst, context))
5355
return;
5456

5557
// check target field
@@ -60,6 +62,37 @@ public Task<INodeVisitor> ValidateAsync(ValidationContext context)
6062
}));
6163
}
6264

65+
private bool SkipAuthCheck(Field fieldAst, ValidationContext context)
66+
{
67+
if (fieldAst.Directives == null || !fieldAst.Directives.Any()) return true;
68+
69+
var includeField = GetDirectiveValue(context, fieldAst.Directives, DirectiveGraphType.Include.Name);
70+
if (includeField.HasValue) return !includeField.Value;
71+
72+
var skipField = GetDirectiveValue(context, fieldAst.Directives, DirectiveGraphType.Skip.Name);
73+
if (skipField.HasValue) return skipField.Value;
74+
75+
return false;
76+
}
77+
78+
private static bool? GetDirectiveValue(ValidationContext context, Directives directives, string directiveName)
79+
{
80+
var directive = directives.Find(directiveName);
81+
if (directive == null) return null;
82+
83+
var operation = !string.IsNullOrWhiteSpace(context.OperationName)
84+
? context.Document.Operations.WithName(context.OperationName)
85+
: context.Document.Operations.FirstOrDefault();
86+
var values = ExecutionHelper.GetArgumentValues(
87+
context.Schema,
88+
DirectiveGraphType.Include.Arguments,
89+
directive.Arguments,
90+
ExecutionHelper.GetVariableValues(context.Document, context.Schema, operation?.Variables, context.Inputs));
91+
92+
values.TryGetValue("if", out object ifObj);
93+
return bool.TryParse(ifObj?.ToString() ?? string.Empty, out bool ifVal) && ifVal;
94+
}
95+
6396
private void CheckAuth(
6497
INode node,
6598
IProvideMetadata type,

0 commit comments

Comments
 (0)