0
0
GraphQLquery~5 mins

Context-based authentication in GraphQL

Choose your learning style9 modes available
Introduction

Context-based authentication helps check who you are before giving access to data. It keeps data safe by using information about the user or request.

When you want to allow only logged-in users to see their own data.
When you need to check user roles before allowing certain actions.
When you want to track who made a request for auditing.
When you want to customize data shown based on user location or device.
When you want to protect sensitive data from unauthorized access.
Syntax
GraphQL
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    // Extract user info from request headers
    const user = getUserFromToken(req.headers.authorization);
    return { user };
  }
});
The context function runs for every request and can add user info.
You can use the context inside resolvers to check user identity or permissions.
Examples
Extracts user info from the request header token and adds it to context.
GraphQL
context: ({ req }) => {
  const user = getUserFromToken(req.headers.authorization);
  return { user };
}
Sets a fixed user in context for testing or development.
GraphQL
context: () => ({
  user: { id: '123', role: 'admin' }
})
Adds the request IP address to context for logging or restrictions.
GraphQL
context: ({ req }) => {
  const ip = req.ip;
  return { ip };
}
Sample Program

This GraphQL server checks the user's token from the request header. Only users with the 'admin' role can get the secret data. Others get errors.

GraphQL
const { ApolloServer, gql } = require('apollo-server');

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

const resolvers = {
  Query: {
    secretData: (parent, args, context) => {
      if (!context.user) {
        throw new Error('Not authenticated');
      }
      if (context.user.role !== 'admin') {
        throw new Error('Not authorized');
      }
      return 'Top secret info';
    }
  }
};

function getUserFromToken(token) {
  if (token === 'admin-token') {
    return { id: '1', role: 'admin' };
  } else if (token === 'user-token') {
    return { id: '2', role: 'user' };
  }
  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}`);
});
OutputSuccess
Important Notes

Always validate tokens carefully to avoid security risks.

Context runs for every request, so keep it fast and simple.

You can add more info to context like user permissions or request details.

Summary

Context-based authentication uses request info to check user identity.

It helps protect data by allowing only authorized users to access it.

Use the context function to add user info for resolvers to check.