graphql / graphiql

GraphiQL & the GraphQL LSP Reference Ecosystem for building browser & IDE tools.
MIT License
15.94k stars 1.71k forks source link

How to use Graphiql when api protected with JWT token. #1771

Closed trevorezwaiver closed 2 years ago

trevorezwaiver commented 3 years ago

I am trying to hit my api that is protected by a JWT token. On login, the JWT token is stored as a cookie. Since it's stored as a cookie, I don't have access to it. I know something like the code below would work, if I could access the cookie, but I can't. Is there any other way to pass the authorization? I really don't want to put the token in local storage.

configs: { type: new GraphQLList(Configs), args: { first: {type: GraphQLInt}, offset: {type: GraphQLInt}, cookieToken: {type: GraphQLString} }, resolve: async (parentValue, args, res) => { let results = await axios.get(http://localhost:5000/configslist/${args.offset}${args.first}, { headers: { 'Authorization': Bearer ${args.cookieToken} } }) .then((res) => { return res.data }) return results; } }

acao commented 3 years ago

i had written up a whole FAQ on this and I don't know where it went?!

what you'll want to do is use parent react component state or context or some such, and pass the auth token to GraphiQL fetcher as you render it

for example, the github v4 api docs - they just render a semi-transparent overlay over the GraphiQL component until you've logged in successfully. you could also have a simple login screen -> GraphiQL flow. you can set the query, fetcher (with headers) and/or schema at any point in the lifecycle

trevorezwaiver commented 3 years ago

i had written up a whole FAQ on this and I don't know where it went?!

what you'll want to do is use parent react component state or context or some such, and pass the auth token to GraphiQL fetcher as you render it

for example, the github v4 api docs - they just render a semi-transparent overlay over the GraphiQL component until you've logged in successfully. you could also have a simple login screen -> GraphiQL flow. you can set the query, fetcher (with headers) and/or schema at any point in the lifecycle

Thanks acao! I'm still super new to this. I think what you are saying is that when I create the JWT/cookie I need to issue it to GraphiQL at the same time. Currently my app request the JWT/Cookie from my server. I also have all my schemas in a schema.js file. Thanks again, I am going to continue to work with your solution and see what happens.

acao commented 3 years ago

yes! for the simplest case and you'll want to render <GraphiQL /> component only once the token is available. so you could have:

const url = "https://acme.com/graphql"
const [token,setToken] = useState(null)

return token ? <Login onLogin={setToken} /> : <GraphiQL fetcher={ /* use the token in the fetch() headers here */} />

I will provide a more full example in the docs soon!

trevorezwaiver commented 3 years ago

acao Rad! I'm starting to see how that will work now. I'm going to try to give this a try tomorrow or tonight if I can break free.

koistya commented 1 year ago

You can inject the following code snippet to make it work with Firebase Auth (ID token):

<script type="module">
  import { initializeApp, getApp } 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: "${env.GOOGLE_CLOUD_PROJECT}",
    appId: "${env.FIREBASE_APP_ID}",
    apiKey: "${env.FIREBASE_API_KEY}",
    authDomain: "${env.FIREBASE_AUTH_DOMAIN}"
  });

  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).onAuthStateChanged((user) => {
    if (user) {
      user.getIdToken().then(token => setAuthHeader(token));
    } else {
      setAuthHeader(null);
    }
  });
</script>

https://www.codementor.io/@koistya/graphiql-with-firebase-auth-251hx5qhz3