Skip to content

Commit 557614b

Browse files
committed
Support [AllowAnonymous] and [Authorize] simultaneously on a field
1 parent e04baf0 commit 557614b

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

src/GraphQL.AspNetCore3/AuthorizationVisitorBase.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,7 @@ public virtual async ValueTask EnterAsync(ASTNode node, ValidationContext contex
5757
_onlyAnonymousSelected.Push(ti);
5858

5959
// Fields, unlike types, are validated immediately.
60-
if (!fieldAnonymousAllowed) {
61-
await ValidateAsync(field, node, context);
62-
}
60+
await ValidateAsync(field, node, context);
6361
}
6462

6563
// prep for descendants, if any

src/Tests/AuthorizationTests.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,37 @@ public async Task EndToEnd(bool authenticated)
751751
actual.ShouldBe(@"{""errors"":[{""message"":""Access denied for field \u0027parent\u0027 on type \u0027QueryType\u0027."",""locations"":[{""line"":1,""column"":3}],""extensions"":{""code"":""ACCESS_DENIED"",""codes"":[""ACCESS_DENIED""]}}]}");
752752
}
753753

754+
[Theory]
755+
[InlineData("Role1", false, false)] // User with Role1, child requires Role2 - should fail at child level
756+
[InlineData("Role2", false, false)] // User with Role2, query requires Role1 - should fail at query level
757+
[InlineData("Role1,Role2", false, true)] // User with both roles - should pass
758+
[InlineData(null, false, false)] // Unauthenticated user - should fail at query level
759+
[InlineData("Role1", true, false)] // User with Role1, child requires Role2 and is anonymous - should fail
760+
[InlineData("Role2", true, true)] // User with Role2, child requires Role2 and is anonymous - should pass
761+
[InlineData("Role1,Role2", true, true)] // User with both roles, child is anonymous - should pass
762+
[InlineData(null, true, false)] // Unauthenticated user, child is anonymous - should fail due as Role2 missing
763+
public void BothAnonymousAndRequirements(string? userRoles, bool childIsAnonymous, bool expectedIsValid)
764+
{
765+
// Set up query to require Role1
766+
_query.AuthorizeWithRoles("Role1");
767+
768+
// Set up child field to require Role2 and optionally be anonymous
769+
_field.AuthorizeWithRoles("Role2");
770+
if (childIsAnonymous)
771+
_field.AllowAnonymous();
772+
773+
// Set up user principal based on test parameters
774+
if (userRoles != null)
775+
{
776+
var roles = userRoles.Split(',');
777+
var claims = roles.Select(role => new Claim(ClaimTypes.Role, role)).ToArray();
778+
_principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie"));
779+
}
780+
781+
var ret = Validate(@"{ parent { child } }");
782+
ret.IsValid.ShouldBe(expectedIsValid);
783+
}
784+
754785
public enum Mode
755786
{
756787
None,

0 commit comments

Comments
 (0)