authorization in graphql in javascript

There are different ways to handle authorization in GraphQL, but one commonly used method is using JSON web tokens (JWT) and middleware like express-jwt.

Here's an example of how to implement authorization in a GraphQL server with JWT and express-jwt middleware:

index.tsx
const express = require('express');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Define schema
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// Define resolver
const root = {
  hello: (args, context) => {
    return `Hello, ${context.user.username}!`;
  },
};

// Set up a GraphQL server
const app = express();

// Set up JWT middleware
// Replace `YOUR_SECRET_KEY` with your own secret key
const jwtCheck = expressJwt({
  secret: 'YOUR_SECRET_KEY',
  algorithms: ['HS256'],
  credentialsRequired: false,
});

// Set up a middleware function to decode the JWT and add `user` to the context
const decodeJwt = (req, res, next) => {
  if (req.user) {
    const user = jwt.decode(req.user, {
      complete: true,
    });
    req.user = user.payload;
  }
  next();
};

// Apply JWT middleware and decode middleware to all requests
app.use(jwtCheck);
app.use(decodeJwt);

// Define GraphQL endpoint
app.use(
  '/graphql',
  graphqlHTTP((req) => ({
    schema: schema,
    rootValue: root,
    context: {
      user: req.user || null,
    },
    graphiql: true,
  }))
);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});
1368 chars
65 lines

In this example, we first define a GraphQL schema with one Query field called hello. We also define a resolver function for the hello field, which returns a personalized greeting based on the username of the authenticated user.

We then set up a GraphQL server using express-graphql. We also set up JWT middleware using express-jwt. The middleware checks the Authorization header of each request for a JWT and decodes it using the specified secret key. If the JWT is valid, the middleware adds the decoded payload to the req.user property.

We also define a middleware function called decodeJwt, which decodes the JWT payload and adds it to the req.user property if the payload is present. We apply both the JWT middleware and decodeJwt middleware to all requests using app.use().

Finally, we define a GraphQL endpoint at /graphql and pass in the schema, root value, and context object. The context object includes the authenticated user object if it exists.

With this setup, you can now make GraphQL requests by including a valid JWT in the Authorization header of your requests. The resolver functions can access the authenticated user object in the context object.

gistlibby LogSnag