I'm getting the following error message when testing queries on a test project: "The feature Authorization is missing the state with the key HotChocolate.Authorization.UserState"
It seems to me the issue is coming form DefaultAuthorizationHandler used by HotChocolate AddAuthorization middleware because the there is no user or claims principal available, during run time in my test project.
I've read similar posts on this topic: HotChocolate Authorization exception on test project where the op was saying he ended up writing a custom AuthorizationHandler that adds a claimsprincipal but he didn't provide any code for his solution.
I'm not sure what is the best way to handle this in my test project.
Here is my code from the test project:
Services = new ServiceCollection()
.AddGraphQLServer()
.AddQueryType<Query>()
.AddAuthorization()
// Registers the filter convention of MongoDB
.AddMongoDbFiltering()
// Registers the sorting convention of MongoDB
.AddMongoDbSorting()
// Registers the projection convention of MongoDB
.AddMongoDbProjections()
// Registers the paging providers of MongoDB
.AddMongoDbPagingProviders()
Executor = Services.GetRequiredService<RequestExecutorProxy>();
Later on I execute a query by passing the query to the ExecuteRequestAsync method:
[Fact]
public async void FetchProjectAuditMasterActionsAllFields()
{
var result = await TestServices.ExecuteRequestAsync(b => b.SetQuery("query{...}"));
result.MatchSnapshot();
}
public static async Task<string> ExecuteRequestAsync(
Action<IQueryRequestBuilder> configureRequest,
CancellationToken cancellationToken = default)
{
await using var scope = Services.CreateAsyncScope();
var requestBuilder = new QueryRequestBuilder();
requestBuilder.SetServices(scope.ServiceProvider);
configureRequest(requestBuilder);
var request = requestBuilder.Create();
await using var result = await Executor.ExecuteAsync(request, cancellationToken);
result.ExpectQueryResult();
return result.ToJson();
}
For anyone having this issue, in the meantime I've managed to find a solution to my own problem. You need to add the ClaimsPrincipal on the QueryRequestBuilder like this:
Where the CreatePrincipal() method is defined like this: