graphql-dotnet / graphql-dotnet/authorization
Authorizing Subscriptions With JWT
- Dominant language
- C#
- Stars
- 160
- Forks
- 38
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
I have some authorizations setup to handle Queries and Mutations like so (simplified)
```
services.AddSingleton(x =>
{
AuthorizationSettings settings = new AuthorizationSettings();
settings.AddPolicy(AuthConstants.USERS_POLICY, p => p.RequireClaim(ClaimTypes.Role));
settings.AddPolicy(AuthConstants.ADMIN_POLICY, p => p.RequireClaim(ClaimTypes.Role, ((int)UserRoles.Administrator).ToString()));
settings.AddPolicy(AuthConstants.SUPERVISOR_POLICY, p => p.RequireClaim(ClaimTypes.Role, ((int)UserRoles.Administrator).ToString(),
((int)UserRoles.Supervisor).ToString()));
return settings;
})
```
Now I'm attempting to add Subscriptions, but it looks like the Authorizations are not working. There didn't seem to be any built-in support for authorizing Subscriptions with JWTs, so I used [this class](https://github.com/graphql-dotnet/server/blob/develop/samples/Samples.Server/AddAuthenticator.cs) for guidance. I can successfully retrieve the token from the connection, validate it, and add it to the HTTP context in an IOperationMessageListener::BeforeHandleAsync
```
public Task BeforeHandleAsync(MessageHandlingContext context)
{
if (context.Message.Type == MessageType.GQL_CONNECTION_INIT)
{
JObject payload = context.Message.Payload as JObject;
if (payload.TryGetValue("Authorization", System.StringComparison.OrdinalIgnoreCase, out JToken authValue))
{
string token = authValue.Value();
if (string.IsNullOrWhiteSpace(token) == false)
{
int start = token.IndexOf(BEARER, System.StringComparison.OrdinalIgnoreCase);
if (start >= 0)
{
token = token.Substring(start + BEARER_LENGTH);
_httpContextAccessor.HttpContext.User = JwtHelper.CreatePrincipal(token);
}
}
}
}
ClaimsPrincipal user = _httpContextAccessor.HttpContext.User;
context.Properties["user"] = user;
return Task.CompletedTask;
}
```
But the subscription endpoint still says that I'm unauthorized when I use `AuthorizeWith`. Is this a bug or how can I authorize Subscriptions using JWTs? Any guidance would be much appreciated
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.