Skip to content

Authorizing Subscriptions With JWT #49

@jonmill

Description

@jonmill

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 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<string>();
                    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions