Manuel
Manuel

Reputation: 9552

How to pass JWT(JSON Web Tokens) for authorization via url/link to graphiql

I'd like to link my web application with graphiql so users can use graphiql without requiring to manually insert the token into the headers section.

How can I pass JWT(JSON Web Tokens) for authorization from my application to graphiql eg via URL, so it is getting set in the headers configuration?

I do know the option of creating a react wrapper app and injecting via fetchers, but would rather like to keep it simpler eg via url.

Thx in advance, I really appreciate your expertise!

Upvotes: 0

Views: 973

Answers (2)

Konstantin Tarkus
Konstantin Tarkus

Reputation: 38428

enter image description here

If you're using GraphiQL IDE provided by Helix GraphQL server, you may find that it's not that trivial to hook it up with Firebase (Google Identity Platform) auth flow.

One way to make it work is to inject the following code snippet into the HTML page containing GraphiQL IDE:

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js";
  import { getAuth } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-auth.js";

  const app = initializeApp({
    projectId: "example",
    appId: "xxxxx",
    apiKey: "xxxxx",
    authDomain: "example.com"
  });

  function setAuthHeader(token) {
    const editor = document.querySelectorAll('.variable-editor .CodeMirror')[1].CodeMirror;
    const headers = JSON.parse(editor.getValue());
    headers.Authorization = token ? "Bearer " + token : undefined;
    editor.setValue(JSON.stringify(headers, null, 2));
  }

  getAuth(app).onIdTokenChanged((user) => {
    if (user) {
      user.getIdToken().then(token => setAuthHeader(token));
    } else {
      setAuthHeader(null);
    }
  });
</script>

Which updates Authorization: Bearer <idToken> header in GraphiQL whenever the user logs in or logs out using Firebase.

Find the full example at https://github.com/kriasoft/relay-starter-kit

Upvotes: 0

Click on "REQUEST HEADERS" on GraphiQL as shown below:

enter image description here

Then, put "Authorization" header and "JWT" keyword with JWT Access Token in REQUEST HEADERS as shown below:

{
  "Authorization": "JWT your_jwt_access_token_here"
}

Be careful, if you omit Double Quotes as shown below, there is an error:

{
  Authorization: JWT your_jwt_access_token_here
}

Again be careful, if you use Single Quotes to make String type values on GraphiQL as shown below, there is an error:

{
  'Authorization': 'JWT your_jwt_access_token_here'
}

Upvotes: 2

Related Questions