Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create user state if it does not exist. #5838

Merged
merged 2 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Security.Claims;
using HotChocolate.Execution;
using Microsoft.Extensions.DependencyInjection;
using static HotChocolate.WellKnownContextData;
Expand All @@ -13,5 +14,12 @@ public void Enrich(IRequestContext context)
var authorizationHandler = context.Services.GetRequiredService<IAuthorizationHandler>();
context.ContextData.Add(AuthorizationHandler, authorizationHandler);
}

if (!context.ContextData.ContainsKey(WellKnownContextData.UserState) &&
context.ContextData.TryGetValue(nameof(ClaimsPrincipal), out var value) &&
value is ClaimsPrincipal principal)
{
context.ContextData.Add(WellKnownContextData.UserState, new UserState(principal));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Security.Claims;
using CookieCrumble;
using HotChocolate.Authorization;
using HotChocolate.Execution;
Expand Down Expand Up @@ -610,6 +611,67 @@ public async Task Skip_Authorize_On_Node_Field()
Assert.Equal(401, value);
}

[Fact]
public async Task Assert_UserState_Exists()
{
// arrange
var handler = new AuthHandler(
resolver: (ctx, _)
=> ctx.ContextData.ContainsKey(WellKnownContextData.UserState)
? AuthorizeResult.Allowed
: AuthorizeResult.NotAllowed,
validation: (ctx, _)
=> ctx.ContextData.ContainsKey(WellKnownContextData.UserState)
? AuthorizeResult.Allowed
: AuthorizeResult.NotAllowed);

var services = CreateServices(
handler,
options =>
{
options.ConfigureNodeFields =
descriptor =>
{
descriptor.Authorize("READ_NODE");
};
});

var executor = await services.GetRequestExecutorAsync();

// act
var result = await executor.ExecuteAsync(
builder =>
builder
.SetQuery(
"""
{
nodes(ids: "abc") {
__typename
}
}
""")
.SetGlobalState(nameof(ClaimsPrincipal), new ClaimsPrincipal()));

// assert
Snapshot
.Create()
.Add(result)
.MatchInline(
"""
{
"errors": [
{
"message": "Unable to decode the id string.",
"extensions": {
"operationStatus": "InvalidData",
"originalValue": "abc"
}
}
]
}
""");
}

private static IServiceProvider CreateServices(
IAuthorizationHandler handler,
Action<AuthorizationOptions>? configure = null)
Expand Down