Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
trevorezwaiver opened this issue Jan 20, 2021 · 5 comments
Closed

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

trevorezwaiver opened this issue Jan 20, 2021 · 5 comments

Comments

@trevorezwaiver
Copy link

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
Copy link
Member

acao commented Jan 21, 2021

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
Copy link
Author

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
Copy link
Member

acao commented Jan 21, 2021

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
Copy link
Author

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
Copy link

koistya commented May 22, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants