0
0
GraphqlHow-ToBeginner · 4 min read

How to Add Authentication to GraphQL APIs Easily

To add authentication to GraphQL, include an authentication check in the server's context function that runs on each request. This lets you verify user credentials (like tokens) before resolving queries or mutations, ensuring only authorized users access data.
📐

Syntax

Authentication in GraphQL is usually handled in the context function of your GraphQL server setup. This function runs on every request and can extract user info from headers or cookies.

Key parts:

  • context: Receives request info, used to pass user data to resolvers.
  • Authorization header: Common place to send tokens like JWT.
  • Resolvers: Check context.user to allow or deny access.
javascript
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    const token = req.headers.authorization || '';
    const user = getUserFromToken(token); // your function to verify token
    return { user };
  },
});
💻

Example

This example shows a simple Apollo Server setup that checks a JWT token from the Authorization header. If the token is valid, the user info is added to context. The resolver then allows access only if the user is authenticated.

javascript
const { ApolloServer, gql } = require('apollo-server');
const jwt = require('jsonwebtoken');

const typeDefs = gql`
  type Query {
    secretData: String
  }
`;

const resolvers = {
  Query: {
    secretData: (parent, args, context) => {
      if (!context.user) {
        throw new Error('Not authenticated');
      }
      return 'This is secret data for ' + context.user.name;
    },
  },
};

function getUserFromToken(token) {
  try {
    if (!token) return null;
    return jwt.verify(token.replace('Bearer ', ''), 'your_secret_key');
  } catch {
    return null;
  }
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    const token = req.headers.authorization || '';
    const user = getUserFromToken(token);
    return { user };
  },
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

  • Not verifying the token properly or skipping verification allows unauthorized access.
  • Forgetting to pass context to resolvers means authentication info is missing.
  • Sending tokens without the Bearer prefix can cause verification failures.
  • Not handling errors gracefully can expose sensitive info or crash the server.
javascript
/* Wrong: No token verification */
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({ user: null }), // no auth check
});

/* Right: Verify token and handle errors */
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    const token = req.headers.authorization || '';
    try {
      const user = jwt.verify(token.replace('Bearer ', ''), 'your_secret_key');
      return { user };
    } catch {
      return { user: null };
    }
  },
});
📊

Quick Reference

Tips for adding authentication to GraphQL:

  • Use context to pass user info to resolvers.
  • Extract tokens from Authorization headers.
  • Verify tokens securely (e.g., JWT).
  • Check user presence in resolvers before returning data.
  • Handle errors without exposing sensitive details.

Key Takeaways

Add authentication logic inside the GraphQL server's context function to check user credentials on each request.
Extract and verify tokens from the Authorization header to identify users securely.
Always check for authenticated user presence in resolvers before returning sensitive data.
Handle token verification errors gracefully to avoid server crashes or data leaks.
Use standard libraries like jsonwebtoken for token verification to simplify implementation.