Skip to content

Custom headers in graphiql.js #1536

Open
@lbhsot

Description

@lbhsot

Is your feature request related to a problem? Please describe.
I'm facing a authentication issue when I use GraphQL playground. My server need a custom header to verify if the request is valid but in graphiql.js have no possible to inject custom header.

Describe the solution you'd like
graphiql.html

    window.GRAPHENE_SETTINGS = {
    {% if subscription_path %}
      subscriptionPath: "{{subscription_path}}",
    {% endif %}
      graphiqlHeaderEditorEnabled: {{ graphiql_header_editor_enabled|yesno:"true,false" }},
      graphiqlShouldPersistHeaders: {{ graphiql_should_persist_headers|yesno:"true,false" }},
      graphiqlInputValueDeprecation: {{ graphiql_input_value_deprecation|yesno:"true,false" }},
    {% if graphiql_headers %}
      graphiqlHeaders: {{ graphiql_headers }}
    {% endif %}
    };

graphiql.js

var headers = {};
  var cookies = ("; " + document.cookie).split("; csrftoken=");
  if (cookies.length == 2) {
    csrftoken = cookies.pop().split(";").shift();
  } else {
    csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value;
  }
  if (csrftoken) {
    headers['X-CSRFToken'] = csrftoken
  }
  if (GRAPHENE_SETTINGS.graphiqlHeaders) {
    var customHeaders = GRAPHENE_SETTINGS.graphiqlHeaders.split(";");
    for (const header of customHeaders) {
      const [key, value] = header.split(":")
      if (key && value) {
        headers[key] = value
      }
    }
  }

graphene_django/views.py

self.render_graphiql(
  request,
  graphiql_headers=self.custom_headers
  ...
)

Usage

GraphQLView.as_view(..., custom_headers="header_key_1:header_value_1;header_key_2:header_value_2")

Describe alternatives you've considered
No alternatives

Additional context
N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions