0
0
GraphQLquery~5 mins

Authentication errors in context in GraphQL

Choose your learning style9 modes available
Introduction

Authentication errors tell us when someone tries to access data without permission. They help keep data safe.

When a user tries to log in with wrong username or password.
When a user tries to access data without logging in.
When a user's login session has expired and they try to use the system.
When a user tries to access data they are not allowed to see.
Syntax
GraphQL
type Query {
  secureData: String
}

const resolvers = {
  Query: {
    secureData(parent, args, context) {
      if (!context.user) {
        throw new AuthenticationError('You must be logged in');
      }
      return 'Secret info';
    }
  }
};
Authentication errors are usually thrown inside resolvers when user info is missing or invalid.
The context object often holds user info after login.
Examples
This checks if the user is missing in context and throws an error.
GraphQL
if (!context.user) {
  throw new AuthenticationError('Not logged in');
}
This checks if the user is an admin before allowing access.
GraphQL
if (!context.user.isAdmin) {
  throw new AuthenticationError('Admin access required');
}
Sample Program

This GraphQL server checks if the user is logged in by looking for a valid token in the request headers. If the token is missing or invalid, it throws an authentication error when trying to get the secret message.

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

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

const resolvers = {
  Query: {
    secretMessage(parent, args, context) {
      if (!context.user) {
        throw new AuthenticationError('You must be logged in to see this message');
      }
      return 'This is a secret message';
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    // Simulate user authentication
    const token = req.headers.authorization || '';
    if (token === 'valid-token') {
      return { user: { id: 1, name: 'Alice' } };
    }
    return {};
  }
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
OutputSuccess
Important Notes

Always check authentication early in your resolver to avoid exposing data.

Use clear error messages so users know why access was denied.

Summary

Authentication errors protect data by stopping unauthorized access.

They are thrown inside resolvers using the context user info.

Check user info in context before returning sensitive data.