Giter Club home page Giter Club logo

Comments (90)

mzohaibqc avatar mzohaibqc commented on May 5, 2024 266

I found a way to fix this problem. On Chrome, you can install an extention ModHeader https://chrome.google.com/webstore/detail/modheader/idgpnmonknjnojddfkpgkljpfnnfcklj which will allow you to modify request or response headers. In this way, you can send Authorization header with each request and graphiql will work fine.

from graphiql.

leebyron avatar leebyron commented on May 5, 2024 156

GraphiQL is generic and doesn't know anything about the network! This is great because you can configure it to use whatever your GraphQL server uses. This is how @skevy was able to build a standalone app version of GraphiQL.

I suggest taking a look at the example - where you see graphQLFetcher is where you can configure your network fetching however you like, in your case by including any authentication details that may be necessary.

Often, when your GraphQL endpoint is behind a authorization feature like this, it is common to expose the GraphiQL tool via a different endpoint on your server.

from graphiql.

KyleAMathews avatar KyleAMathews commented on May 5, 2024 142

Download @skevy's https://github.com/skevy/graphiql-app and your header. I have the same setup as you and use this daily.

from graphiql.

MarkAndrewJohnson avatar MarkAndrewJohnson commented on May 5, 2024 129

@leebyron I would agree being generic is a reason not to automate everything. I would think, though, that being generic is exactly why it DOES makes sense to have a field allowing custom headers to be set manually by the user!

I'm also unclear as to your last statement. It doesn't avoid the need for auth tokens to be pushed around.

from graphiql.

cancan101 avatar cancan101 commented on May 5, 2024 122

Any reason to close this issue and opposed to adding the header editor to the (main) graphiql?

from graphiql.

khaledosman avatar khaledosman commented on May 5, 2024 30

its really sad that this is still open after 3 years... All the solutions provided in the comments are just workarounds or reference to other tools. It shouldn't be too complicated to implement some form in the UI to add the headers.. Are there any intentions to implement this?

I'm currently using Insomnia which is like Postman for graphQL, but I'd rather just use graphiql.

from graphiql.

benjie avatar benjie commented on May 5, 2024 28

You could also use the headers editor:

Screenshot_20210218_145143

from graphiql.

hunt avatar hunt commented on May 5, 2024 27

Actually, I use a simple solution between our GraphQL development process. If you GraphQL server parse a access_token from querystring more than just a http header.

We can pass access_token in query string to the browser's address bar at our GraphiQL page ?access_token=xxx&query=... then GraphiQL will send access_token to req.query

I parse a token with something like express-bearer-token

from graphiql.

iamsaso avatar iamsaso commented on May 5, 2024 27

Easy implementation to get JWT Token support in GraphiQL

https://gist.github.com/sasso/3c3d728e0049d5b66a2c19b349b7f164

screenshot 2017-07-07 09 46 20

from graphiql.

acao avatar acao commented on May 5, 2024 21

I've decided - given that we are doing one final 1.0.0 (pre rewrite/plugins) stable release for GraphiQL, we get to have one feature.

And that's a headers tab. Whoever wants to, feel free to add a single tab for headers in a PR, and if we can get it merged next week, we can at least have that until we have a stable beta plugin API!

from graphiql.

imolorhe avatar imolorhe commented on May 5, 2024 20

@AndreyMalykhin You can use https://altair.sirmuel.design/ also.

from graphiql.

yami12376 avatar yami12376 commented on May 5, 2024 14

When there will be feature to add headers for tests by default in GraphiQL ?

from graphiql.

mrceperka avatar mrceperka commented on May 5, 2024 13

This one works for me :)
image

from graphiql.

johndpope avatar johndpope commented on May 5, 2024 11

I got here from google search found answer in issue below - in the graphql - http headers at bottom just add

{
"Authorization": "Bearer your-token-goes-here"
}
howtographql/howtographql#448

UPDATE
N.B. - actually this is the wrong answer for graph-i-Ql which seems to be missing this component / I didn't realize. I've left this answer above.

Screen Shot 2019-08-14 at 7 41 37 am

You can use prisma graphql playground - https://github.com/prisma/graphql-playground
This repo should probably yield to that code base / or cherry pick the headers code to get this in.

from graphiql.

connorshea avatar connorshea commented on May 5, 2024 9

Yep, if you upgrade to 1.0.0 you can enable the headers editor :D I have it enabled on my app here.

The code I use to create the GraphiQL instance with the headers editor enabled and pre-filled is this:

let graphQLFetcher = (graphQLParams, opts = { headers: {} }) => {
  return fetch(window.location.origin + '/graphql', {
    method: 'post',
    headers: Object.assign({ 'Content-Type': 'application/json', 'User-Agent': 'vglist.co GraphiQL' }, opts.headers),
    body: JSON.stringify(graphQLParams),
  }).then(response => response.json());
}

ReactDOM.render(
  React.createElement(GraphiQL, {
    fetcher: graphQLFetcher,
    headerEditorEnabled: true,
    headers: '{\n  "X-User-Email": "[email protected]",\n  "X-User-Token": "API_TOKEN_HERE"\n}'
  }),
  document.getElementById("graphiql-injection-point")
);

We should probably update the README to mention give a code example for using the headers editor and sending headers with the GraphiQL requests.

from graphiql.

vitalcode avatar vitalcode commented on May 5, 2024 8

Look at auth-graphiql (https://github.com/vitalcode/auth-graphiql) that wraps GraphiQL providing support for bearer token and arbitrary URL. Great for testing GraphQL services secured with OAuth 2.0.

from graphiql.

acao avatar acao commented on May 5, 2024 8

we will be providing an example soon, but all of this is possible with the current GraphiQL

from graphiql.

sorenhoyer avatar sorenhoyer commented on May 5, 2024 6

I don't get why on earth we cannot have a "headers" section just like the "query variables" section. Seems awkward, now 4 years later...

from graphiql.

acao avatar acao commented on May 5, 2024 6

thanks everyone!

for the record, and you can see this in the GraphiQL readme now, you can enable the headers editor with headersEditorEnabled prop, and even use a static headers string prop to set the default headers in the headers editor, and users can override this per-request in the headers tab.

thanks @connorshea for your work and @harshithpabbati and @ncthbrt for helping to review!

any new features for this will be part of [email protected] plugins, as, following the Spec WG, HTTP-driven functionality is now part of a seperate GraphQL HTTP Spec. We must honor the HTTP agnostic default spec by default, and then will have http plugins to follow the HTTP spec.

consider this a bonus for the very long feature freeze as we had to spend so long preparing GraphiQL for the rewrite, performing the rewrite, and are now working on the plugin spec. the new SDK-oriented approach will be very rewarding!

from graphiql.

emjaksa avatar emjaksa commented on May 5, 2024 5

Hope this helps. How I implimented custom headers for my GraphiQL interface with a express-graphql server.

Modify your server to handle post requests from one endpoint and get requests to the graphiql interface on another.

app.post(
  '/graphql',
  expressGraphQL({
    schema: GraphQLSchema,
    graphiql: false, // Disable graphiql for posts requests
  }),
)

app.get(
  '/graphql',
  expressGraphQL({
    schema: GraphQLSchema,
    graphiql: true, // Enable graphiql for get requests
  }),
)

Basically you need to create a new index.html for your GraphiQL interface and add it to your servers public directory i.e. <public-path>/graphql/index.html. In that file you can modify the fetch function to send any additional headers in your requests. I got my index.html from the graphiql example.

I use webpack and the html-webpack-plugin to bundle the index.html. This allows it to get the correct version of graphql used in my project from the CDN. Below is an example of my webpack config and my ejs template of the index.html.

webpack.config.js

new HtmlWebpackPlugin({
  filename: 'graphql/index.html', // Write the file to <public-path>/graphql/index.html
  inject: false, // Do not inject any of your project assets into the template
  GRAPHQL_VERSION: packageJSON.dependencies.graphql.replace(/[^0-9.]/g, ''), // Get the graphql version from my package.json
  template: 'graphiql.ejs', // path to template
}),

graphiql.ejs

<!--
 *  Copyright (c) Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the license found in the
 *  LICENSE file in the root directory of this source tree.
-->
<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        height: 100%;
        margin: 0;
        width: 100%;
        overflow: hidden;
      }
      #graphiql {
        height: 100vh;
      }
    </style>

    <!--
      This GraphiQL example depends on Promise and fetch, which are available in
      modern browsers, but can be "polyfilled" for older browsers.
      GraphiQL itself depends on React DOM.
      If you do not want to rely on a CDN, you can host these files locally or
      include them directly in your favored resource bunder.
    -->
    <script src="//cdn.jsdelivr.net/es6-promise/4.0.5/es6-promise.auto.min.js"></script>
    <script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
    <script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>
    <script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>

    <link href="//cdn.jsdelivr.net/npm/graphiql@<%= htmlWebpackPlugin.options.GRAPHQL_VERSION %>/graphiql.css" rel="stylesheet" />
    <script src="//cdn.jsdelivr.net/npm/graphiql@<%= htmlWebpackPlugin.options.GRAPHQL_VERSION %>/graphiql.min.js"></script>
  </head>
  <body>
    <div id="graphiql">Loading...</div>
    <script>

      /**
       * This GraphiQL example illustrates how to use some of GraphiQL's props
       * in order to enable reading and updating the URL parameters, making
       * link sharing of queries a little bit easier.
       *
       * This is only one example of this kind of feature, GraphiQL exposes
       * various React params to enable interesting integrations.
       */

        // Parse the search string to get url parameters.
      var search = window.location.search;
      var parameters = {};
      search.substr(1).split('&').forEach(function (entry) {
        var eq = entry.indexOf('=');
        if (eq >= 0) {
          parameters[decodeURIComponent(entry.slice(0, eq))] =
            decodeURIComponent(entry.slice(eq + 1));
        }
      });

      // if variables was provided, try to format it.
      if (parameters.variables) {
        try {
          parameters.variables =
            JSON.stringify(JSON.parse(parameters.variables), null, 2);
        } catch (e) {
          // Do nothing, we want to display the invalid JSON as a string, rather
          // than present an error.
        }
      }

      // When the query and variables string is edited, update the URL bar so
      // that it can be easily shared
      function onEditQuery(newQuery) {
        parameters.query = newQuery;
        updateURL();
      }

      function onEditVariables(newVariables) {
        parameters.variables = newVariables;
        updateURL();
      }

      function onEditOperationName(newOperationName) {
        parameters.operationName = newOperationName;
        updateURL();
      }

      function updateURL() {
        var newSearch = '?' + Object.keys(parameters).filter(function (key) {
          return Boolean(parameters[key]);
        }).map(function (key) {
          return encodeURIComponent(key) + '=' +
            encodeURIComponent(parameters[key]);
        }).join('&');
        history.replaceState(null, null, newSearch);
      }

      // Defines a GraphQL fetcher using the fetch API. You're not required to
      // use fetch, and could instead implement graphQLFetcher however you like,
      // as long as it returns a Promise or Observable.
      function graphQLFetcher(graphQLParams) {
		// Get token from local storage
      	var token = localStorage.getItem('token')

        // This example expects a GraphQL server at the path /graphql.
        // Change this to point wherever you host your GraphQL server.
        return fetch('/graphql', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': token ? 'Bearer '+ token : null,
          },
          body: JSON.stringify(graphQLParams),
          credentials: 'include',
        }).then(function (response) {
          return response.text();
        }).then(function (responseBody) {
          try {
            return JSON.parse(responseBody);
          } catch (error) {
            return responseBody;
          }
        });
      }

      // Render <GraphiQL /> into the body.
      // See the README in the top level of this module to learn more about
      // how you can customize GraphiQL by providing different values or
      // additional child elements.
      ReactDOM.render(
        React.createElement(GraphiQL, {
          fetcher: graphQLFetcher,
          query: parameters.query,
          variables: parameters.variables,
          operationName: parameters.operationName,
          onEditQuery: onEditQuery,
          onEditVariables: onEditVariables,
          onEditOperationName: onEditOperationName
        }),
        document.getElementById('graphiql')
      );
    </script>
  </body>
</html>

from graphiql.

estaub avatar estaub commented on May 5, 2024 4

FWIW... In dev mode only, I've set up my server to save the most recent valid token used for the graphql endpoint, and slap it on any subsequent graphiql-driven queries (where the referer header is graphiql). I just sign into the app and then can use graphiql at will.

from graphiql.

AndreyMalykhin avatar AndreyMalykhin commented on May 5, 2024 4

I've ended up passing access token through Graphiql's Query Variables pane:

{ "accessToken": "azaza" }

from graphiql.

benjie avatar benjie commented on May 5, 2024 3

@sorenhoyer The reason is that GraphQL is not a HTTP API, it's a function call. It can be consumed locally in your programming language of choice, or over a custom TCP/UDP protocol, or via HTTP, or via Websockets, or through IPC, or through any number of other transports. Headers are only used for the HTTP transport (and, possibly, for websockets, although typically they're not used there by clients). So headers are a concern outside of GraphiQL, only the fetcher function needs to know about them, and that function also lives outside of GraphiQL. You can already add your own interface for managing headers outside of the main GraphiQL component, and you can even add a button inside of GraphiQL to open said interface - this is what I do in PostGraphile's --enhance-graphiql mode in case you want to see an example.

In GraphiQL v1 we're planning to add a plugin system where you can easily insert these "external concerns" into the GraphiQL interface, and a preset system with sharable plugin configurations for a particular use case. We're hoping this will enable people to use a HTTP preset that will pull in common HTTP concerns such as headers, URL bar, cookie configuration, etc. so you can get the interface you want with minimal effort. We've only recently started on this project so it's still a while away (most of us are independent open source developers doing this in our spare time, and only became maintainers very recently) but progress is good.

from graphiql.

vinny42 avatar vinny42 commented on May 5, 2024 3

One last FYI:

We've taken the previous advice and ditched graphiql as "unusable for our purpose".

"While it is true that the majority of the cases so far have used HTTP as a transport mechanism, that is solely as a result of the use cases that exist."

Yes, the majority of use cases are HTTP, that's the point; there is no benefit to being network-protocol-agnostic and refusing to add features for HTTP in a tool that is pretty much only used over HTTP is... I'll let you fill in the bits where I might say bad things.

Thanks for the response, I hope GraphiQL will some day be a good alternative again.

from graphiql.

greghaygood avatar greghaygood commented on May 5, 2024 2

@AndreyMalykhin +1 to Altair over the GraphiQL client if only for the ability to edit the headers when my tokens change (rather than deleting and re-entering them).

from graphiql.

nitrnitr avatar nitrnitr commented on May 5, 2024 2

What about

GraphiQL::Rails.config.headers['Authorization'] = -> (context) do
  "your jwt"
end

on the graphiql.rb initializer

from graphiql.

acao avatar acao commented on May 5, 2024 2

You can customize headers as they do here, with a custom fetcher:
https://github.com/graphql/graphiql#getting-started

from graphiql.

SephReed avatar SephReed commented on May 5, 2024 2

that’s exactly how it is intended to be used.

It's awful UX. I'm having to parse through this issue to get the gist, so I can look into the docs and figure out how to reimplement from scratch something which I already had running through another means, all for the sake of adding basic functionality. I get the design principle you're operating by, modularity is important. But everything in moderation.

This is what I would do:

props { 
  showHeaderInputComponent: boolean; // defaults to false
} 

Simple, backwards compatible, easy to understand, doesn't ask the world of the user. There is no way this wouldn't be a better UX than what exists right now.

from graphiql.

luisdav86 avatar luisdav86 commented on May 5, 2024 2

I used this chrome extentions thata allows to send headers https://chrome.google.com/webstore/detail/altair-graphql-client/flnheeellpciglgpaodhkhmapeljopja

from graphiql.

harshithpabbati avatar harshithpabbati commented on May 5, 2024 2

As header tab is added to GraphiQL now we can close this issue right @acao?

from graphiql.

acao avatar acao commented on May 5, 2024 2

released #1593 as [email protected], enjoy!

from graphiql.

njlr avatar njlr commented on May 5, 2024 2

The request headers box works a treat!

const editor = (<GraphiQL headerEditorEnabled={true} fetcher={graphQLFetcher} />);

ReactDOM.render(editor, document.getElementById('graphiql-app'));

However, you must pass the headers through in your fetcher.

For example:

const graphQLFetcher = async (graphQLParams, opts) => {
  const { headers = {} } = opts;

  const response = await fetch('/graphql', {
    method: 'post',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      ...headers,
    },
    body: JSON.stringify(graphQLParams),
  });

  return response.json();
};

from graphiql.

Akifcan avatar Akifcan commented on May 5, 2024 2
graphqlHTTP({
    schema,
    rootValue,
    graphiql: {
      headerEditorEnabled: true
    }
  })

from graphiql.

jasonmorita avatar jasonmorita commented on May 5, 2024 1

For those still having this issue, my coworker came up with a cheap solution (in Express in my case). Have your GraphiQL answer at another endpoint as Lee said above and apply basic-auth to that, where you can supply your JWT, add it to the headers and then let express-jwt pick it up in the next middleware.

from graphiql.

gauravmakkar avatar gauravmakkar commented on May 5, 2024 1

@emjaksa Your code is working fine with query operations, what about subscriptions?...

from graphiql.

psamd avatar psamd commented on May 5, 2024 1

I use passport-http-bearer to parse token on my express server. It parses token from header as well as access_token from query string.

So I add the access_token in the GraphQL endpoint of GraphiQL. Here is my code.

app.get('/graphiql', graphiqlExpress({ endpointURL: '/graphql?access_token=<token>&' }));

This authenticates all requests made by GraphiQL

from graphiql.

praveenweb avatar praveenweb commented on May 5, 2024 1

@khaledosman - We have a forked version of GraphiQL which adds a header UI. It comes with a configurable endpoint and headers and is hosted online at https://graphiql-online.com.

The source of the fork is here.

Hope its helpful for some people :)

from graphiql.

sorenhoyer avatar sorenhoyer commented on May 5, 2024 1

Thanks for your elaborate answer @benjie and good luck on your future work on graphiql.

For now, for those of us in need of a graphiql-ish interface, with headers support, I can recommend: https://chrome.google.com/webstore/detail/graphiql-feen/mcbfdonlkfpbfdpimkjilhdneikhfklp

from graphiql.

SephReed avatar SephReed commented on May 5, 2024 1

I guess what I'm really trying to say is, you've made a wonderful project. It's very nice and I don't mean to be a bother.

from graphiql.

khaledosman avatar khaledosman commented on May 5, 2024 1

@Neitsch a setup example/readme would be a good start.

I think most people use the graphiql middleware and don't setup/use the react component manually, so I'd expect to bypass the component configuration all together and have some form for the headers rendered as part of the component or hidden behind a button that takes care of this by default.

from graphiql.

Neitsch avatar Neitsch commented on May 5, 2024 1

@khaledosman - ah, apologies if I missed that before. That sounds pretty reasonable, especially small setups don't want to go through the trouble of setting all that up. I briefly looked into this. The key challenge is that express-graphql basically only gives you server side configuration options. There are a few things we could attempt:

  • Modify https://github.com/graphql/express-graphql/blob/master/src/renderGraphiQL.js to somehow include the jwt token. Maybe a configuration key could be a stringified function that does whatever you want to do to set the token (gross solution, but works for everyone)
  • Fork express-graphql and make it work for your case. I would anticipate that it's pretty low effort, but it's a headache to maintain.

Neither solution is particularly good, but that's the only two I can come up with right now. I'll keep thinking about it some more. Thanks again for the input!

from graphiql.

khaledosman avatar khaledosman commented on May 5, 2024 1

For some inspiration this is how prisma's playground does it which is built on top of graphiql afaik. I can just enter a JSON object in the headers field which gets sent to the server. The new Apollo Server v2 now includes playground by default instead of graphiql.

image

from graphiql.

gsugambit avatar gsugambit commented on May 5, 2024 1

I definitely think it's easier to use something like mod header to solve this problem. It's avaiable in chrome or firefox

from graphiql.

penx avatar penx commented on May 5, 2024 1

@acao is this via the plugin system (in v1.0.0-alpha?) previously mentioned by @benjie ?

In GraphiQL v1 we're planning to add a plugin system

from graphiql.

acao avatar acao commented on May 5, 2024 1

the plugin system will make it easier to provide a nice UI for this. there are going to be quite a few more alpha versions before we have a plugin system

this is all possible currently though, in 0.7.5 or the alpha, so i had hoped to provide a full auth example before I got too deep into working on monaco or the react refactor for plugins

from graphiql.

acao avatar acao commented on May 5, 2024 1

@connorshea excellent point, yes.

possibly we can add custom headers to the graphiql cdn exmaple?

from graphiql.

jonaskello avatar jonaskello commented on May 5, 2024 1

The headerEditorEnabled is great :-). Is there also some way to include those headers when graphiql asks for the schema? It seems like graphQLFetcher is also used for fetching the schema but in that case opts have empty headers (at least from my limited testing).

from graphiql.

acao avatar acao commented on May 5, 2024 1

to confirm, @jonaskello it was not added. i will pivot to fix this issue!

from graphiql.

jonaskello avatar jonaskello commented on May 5, 2024 1

@acao I can confirm it works! Thanks :-)

from graphiql.

acao avatar acao commented on May 5, 2024 1

@penx thanks for the catch, will update!

your middleware looks great but it exposes a huge template injection attack surface - exposing xss and other potential attack vectors! i had to issue a CVE for graphql playground and issue a security fix for the same exact reasons. playground repo now has an example with a readme that explains all of this

we will be rolling our own middeware packages soon when i have time to get to it. there is still an open PR that needs cleanup if you want to create a new PR based off that to help advance that! We actually use ReactDOM/server in that PR there, but an xss filtered template tag implementation ala the new playground fix would be welcome as well. you can introduce several new typescript packages if you want, or just a basic underling renderer method like playground-html

from graphiql.

m-thirumal avatar m-thirumal commented on May 5, 2024 1

Screen Shot 2022-09-23 at 6 57 08 PM
Add Authentication in the UI itself

from graphiql.

sulliwane avatar sulliwane commented on May 5, 2024

@KyleAMathews awesome, I will give it a shot (my main computer is linux distro though...). thanks

from graphiql.

skevy avatar skevy commented on May 5, 2024

@sulliwane - I'm sure it would compile on Linux - just haven't tried.

from graphiql.

sulliwane avatar sulliwane commented on May 5, 2024

I just tried npm install && npm start under linux (ubuntu 14.04) and graphiql-app-V0.3.1, but got blank screen, see here: skevy/graphiql-app#10

I close this issue as I have the answer now.

from graphiql.

sulliwane avatar sulliwane commented on May 5, 2024

No reason, indeed it would be nice if we could set the header directly into graphiql app. (I'm using graphiql-app right now.)

from graphiql.

eugenehp avatar eugenehp commented on May 5, 2024

@MarkAndrewJohnson @sulliwane @cancan101 @KyleAMathews Guys, it would be interesting to get your opinion on this graphql/express-graphql#101

from graphiql.

PetrSnobelt avatar PetrSnobelt commented on May 5, 2024

@Sasso Thanks, but your old version does not support websockets :-(

from graphiql.

wincent avatar wincent commented on May 5, 2024

Thanks for sharing @emjaksa.

from graphiql.

mkanand33 avatar mkanand33 commented on May 5, 2024

I have a question about graphene authentication...how can I create different tokens for two different logins using graphene -jwt? I want to return a token for user login and also a token for manual admin login? how can I do both?

from graphiql.

westpole avatar westpole commented on May 5, 2024

I got here from google search found answer in issue below - in the graphql - http headers at bottom just add

{
"Authorization": "Bearer your-token-goes-here"
}
howtographql/howtographql#448

@johndpope GraphiQL has only "Query variables" section. It does not have "http headers". How did you get that section? What type of UI do you use to test GraphQL queries?

from graphiql.

christophermlne avatar christophermlne commented on May 5, 2024

@westpole https://github.com/absinthe-graphql/absinthe_plug/blob/master/lib/absinthe/plug/graphiql.ex

Make sure you have configured the correct interface.
If you have the correct interface, there is a button you can push to access the headers functionality

from graphiql.

SephReed avatar SephReed commented on May 5, 2024

I'm really confused. In what way is graphiql useful without being able to access authorized data? Is there something I'm missing here? I can't think of any use cases in which I wouldn't eventually need to pass an auth token.

from graphiql.

acao avatar acao commented on May 5, 2024

The custom fetcher allows you to prescribe any http request pattern you want, you just need to provide the prop to the component.

from graphiql.

acao avatar acao commented on May 5, 2024

@SephReed the graphiql readme has several examples if you look, you just have to follow the link from the readme

from graphiql.

SephReed avatar SephReed commented on May 5, 2024

I've implemented a custom fetcher, and am injecting custom ui. I had been using https://github.com/graphql/express-graphql, but it's "auto graphiql" feature is useless as vanilla graphiql. So now I'm having to reimplement a bunch of stuff.

I don't think graphiql is very useful alone. It seems you kind of have to hack it before it does what it really, really seems like it already should.

from graphiql.

benjie avatar benjie commented on May 5, 2024

That’s not hacking it, that’s exactly how it is intended to be used.

GraphiQL is the building blocks with which you can make a custom GraphQL IDE, and has a very well defined boundary: you worry about the transport and all the transport concerns (via the fetcher function) and GraphiQL worries about the text editing and GraphQL features/documentation.

from graphiql.

vinny42 avatar vinny42 commented on May 5, 2024

"That’s not hacking it, that’s exactly how it is intended to be used."

That sounds like a very very poor excuse not to have to do work :-)
In the end; the majority of applications for graphiql require that it sends headers. The fact that it cannot do so without the user changing code is ridiculous.

This issue has been open for four years, you could save us all a ton of misery by just implementing a basic version of this feature and let whoever needs to override it do so.

I'm sorry, it's just ridiculous.

from graphiql.

imolorhe avatar imolorhe commented on May 5, 2024

@SephReed @vinny42 The core of the GraphiQL tool isn't specific to HTTP as a transport mechanism (that's what @benjie is saying). While it is true that the majority of the cases so far have used HTTP as a transport mechanism, that is solely as a result of the use cases that exist.

On the other hand, the GraphiQL team was recently restructured and already have this implementation in mind, to make GraphiQL pluggable (#829) such that there would be plugins providing some of these features, and also presets that bundle plugins together as they make sense for certain scenarios.

The suggestions here are for working with headers in the current GraphiQL version, and how that can be achieved. Most likely there wouldn't be any modifications to this current (soon to be old) version, and if you don't like the approaches suggested, you could consider other tools for now (there's a number of them available) until the GraphiQL v1.0.0 is released.

Final note: the members of the team maintaining GraphiQL are opensource contributors!

from graphiql.

SephReed avatar SephReed commented on May 5, 2024

the members of the team maintaining GraphiQL are opensource contributors

Who runs the internal politics though? I highly doubt that everyone collectively agreed "making http easy is bad." God speed to open-source contributors, but using them as a human shield for what is almost certainly a top down decision is kind of cheap, eh?

from graphiql.

Neitsch avatar Neitsch commented on May 5, 2024

@SephReed - would you mind laying out how we can improve and make concrete suggestions?
Above you made a suggestion about using a different props structure, but I am getting a feeling that there is something overarching missing for you to ramp up on GraphiQL quickly.
Open source is great, because people with different ideas come together. Therefore I value your input. I'd be more than happy to review/approve any pull requests that make it even easier to use or improve the documentation :)

from graphiql.

SephReed avatar SephReed commented on May 5, 2024

Gladly.

I think it's important to have configuration and I also think it's also important to have user friendly defaults. In terms of pretty much any javascript implementation of graphiql, it seem safe to assume that a good default for fetcher is just fetch pointed at "/graphql." This definitely wouldn't cover every use case, but it's a good starting place.

Following is about all the code I think it should take to setup graphiql, with fetch, pointed to an arbitrary endpoint, with a header component added to the mix:

GraphiQL.renderIn("graphiql", {
  fetcher: "/gql-endpoint",
  showHeaderInputComponent: true,
});

Having 20-50 lines of boilerplate to achieve a simple api with jwt authentication is just a oppressive nuisance when it so easily could be supplied by a tiny function like the one above. This would cover most api use cases... all the ones I can think of at least, but definitely not all. Still, by default, this seems like all it should really take to get a project with graphiql up and running.

from graphiql.

Haseeb717 avatar Haseeb717 commented on May 5, 2024

Is there any way to send header from Graphiql now? which something official from graphiql

from graphiql.

khaledosman avatar khaledosman commented on May 5, 2024

@SephReed - would you mind laying out how we can improve and make concrete suggestions?
Above you made a suggestion about using a different props structure, but I am getting a feeling that there is something overarching missing for you to ramp up on GraphiQL quickly.
Open source is great, because people with different ideas come together. Therefore I value your input. I'd be more than happy to review/approve any pull requests that make it even easier to use or improve the documentation :)

With no way to set authentication headers the library is unusable for most people, most people don't build demo todo apps, but real world apps for customers and corporates, so authentication is kinda important.

With no workarounds or recommended way to do it in a README or a documentation file, you're pushing people away from using your open-source tools because you don't even acknowledge it as a typical normal usecase that everyone is going to stumble upon, which is why everyone else in this thread is suggesting an alternative library.

My question is, As a contributor to this library, have you ever used this tool before? have you ever needed to build authentication? if yes, how did you do it?

The cost/effort for building this is little to none compared to the benefit, yet you don't see it as something that should be part of the interface, this issue has been around for 4 years now and its only going to get more comments by more frustrated developers.

from graphiql.

Neitsch avatar Neitsch commented on May 5, 2024

@khaledosman - thank you for your input. Would you mind help me understand it in some more detail? Are you looking for an explicit method for setting the HTTP headers? At this point I believe you can do something like this:

// This is where you can choose what auth headers to add
function headerGenerator() {
  return {
    'Authorization': 'Bearer <your token goes here>',
  }
}

// Semi generic GraphQL query execution method
function graphQLFetcher(additionalHeadersFunction) {
  return function(graphQLParams) {
    return fetch('/graphql', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...additionalHeadersFunction()
      },
      body: JSON.stringify(graphQLParams),
      credentials: 'include',
    }).then(function(response) {
      return JSON.parse(response.text());
    });
  }
}

ReactDOM.render(
  React.createElement(GraphiQL, {
    fetcher: graphQLFetcher(headerGenerator),
  }),
  document.getElementById('graphiql')
);

This level of effort appears relatively low to me. Would you mind elaborating what you would like to see? Am I missing anything that this solution fundamentally does not deliver? Would you like to see this as a setup in the example package of the repo?

from graphiql.

aamod1990 avatar aamod1990 commented on May 5, 2024

My /graphql route is protected by JWT token, so every HTTP request needs to set:

 headers: {
      Authorization: 'Bearer ' + token
    }

To get through the authentication middleware and hit /graphql.

How to manage this authentication step when using graphiql ? graphiql is so convenient, it's a pity to not use it :(
thanks for any suggestion!

Currently we are using Modify Headers add ons to pass the token in our graphql

from graphiql.

acao avatar acao commented on May 5, 2024

Just specify that header when creating your required fetcher!

from graphiql.

rs-ds avatar rs-ds commented on May 5, 2024

For firefox users, here is the Modify Header Value addon: https://addons.mozilla.org/en-US/firefox/addon/modify-header-value/?src=search

from graphiql.

hassaantariq50 avatar hassaantariq50 commented on May 5, 2024

I found a way to fix this problem. On Chrome, you can install an extention ModHeader https://chrome.google.com/webstore/detail/modheader/idgpnmonknjnojddfkpgkljpfnnfcklj which will allow you to modify request or response headers. In this way, you can send Authorization header with each request and graphiql will work fine.

how to use it? please guide me

from graphiql.

connorshea avatar connorshea commented on May 5, 2024

I've opened a draft PR for this :) #1543

from graphiql.

acao avatar acao commented on May 5, 2024

I'm deep into 2.0.0 plugin API now, but possibly @connorshea can add that for another 1.0.0 release? I should have caught that in the review, my bad.

from graphiql.

connorshea avatar connorshea commented on May 5, 2024

👍 @acao I think we can close this now :)

from graphiql.

acao avatar acao commented on May 5, 2024

to add, if there are any more bugs with this new feature, we will gladly introduce them to 1.0.x patches :)

from graphiql.

jcarroll2007 avatar jcarroll2007 commented on May 5, 2024

for the record, and you can see this in the GraphiQL readme now,

@acao I'm not seeing this in the readme. Would you possibly mind sharing a link to docs on how to use this feature?

Found it! https://github.com/graphql/graphiql/blob/241b81ddf8b8fe2fee23eb8674b782ae53314def/packages/graphiql/README.md#props

from graphiql.

penx avatar penx commented on May 5, 2024

for the record, and you can see this in the GraphiQL readme now, you can enable the headers editor with headersEditorEnabled prop

@acao you may want to edit this to save people time trying to figure out why it doesn't work - it's headerEditorEnabled not headersEditorEnabled

(edit - shameless plug - I just made this, feedback welcomed https://github.com/penx/graphiql-middleware )

from graphiql.

craigmit avatar craigmit commented on May 5, 2024

Easy implementation to get JWT Token support in GraphiQL

https://gist.github.com/sasso/3c3d728e0049d5b66a2c19b349b7f164

screenshot 2017-07-07 09 46 20

This worked great, except the graphiql screen falls off the bottom of the page.

Here's a version using flexbox that aligns it properly: https://gist.github.com/craigmit/44499818664fc34083f2aa96069f0636

from graphiql.

craigmit avatar craigmit commented on May 5, 2024

Thanks @benjie

I didn't see that Request Headers were now available.

I modified the new GraphiQL html, to automatically set the auth header from a # param (so you can call it directly from your application, automatically setting the Authorization header):

https://gist.github.com/craigmit/0cce78ffe33ca3551fbcc35016e8b3e2

Usage is:

graphiqlSetAuth.html#[JWT_TOKEN]

and it will set the Authorization header for you.

The only change to the original graphiql html was the addition of:

const tokenParam = window.location.hash.substr(1);

if (tokenParam) {
  headers = {"Authorization": "Bearer " + tokenParam}
  window.history.replaceState({}, document.title, window.location.href.split('#')[0]);
}

from graphiql.

cedricDevWP avatar cedricDevWP commented on May 5, 2024

@m-thirumal hello, i try to configure api platform with jwt and graphql but I can’t do it… all the time I have 403 when I use security granted…

can you explain how have you configure security.yaml (and other file maybe) to make work pls 😕 ?

from graphiql.

KenEucker avatar KenEucker commented on May 5, 2024

I have been digging through this thread trying to find a way to pass a header, the authorization header, to Graphiql in the request. I am running Graphiql in an iFrame from localhost:8000/graphql and I want to be able to do something like localhost:8000/graphql?headers=serializedheadersstring and have the header values be populated into the editor for all tabs.

Is this possible?

from graphiql.

njlr avatar njlr commented on May 5, 2024

I have been digging through this thread trying to find a way to pass a header, the authorization header, to Graphiql in the request. I am running Graphiql in an iFrame from localhost:8000/graphql and I want to be able to do something like localhost:8000/graphql?headers=serializedheadersstring and have the header values be populated into the editor for all tabs.

Is this possible?

Not a solution but a work-around. You can run a local proxy that puts the GraphiQL UI and the GraphQL endpoint on the same port then the headers are shared automatically.

from graphiql.

koistya avatar koistya commented on May 5, 2024

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

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

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

240006671-eb7c1db1-f6a8-42bb-9392-5161722ba559

from graphiql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.