Authentication vs Authorization in GraphQL: Key Differences and Usage
Authentication in GraphQL verifies who the user is, while authorization determines what the user is allowed to do. Authentication checks identity, often via tokens, and authorization checks permissions to access specific data or actions.Quick Comparison
Here is a quick side-by-side comparison of authentication and authorization in GraphQL.
| Factor | Authentication | Authorization |
|---|---|---|
| Purpose | Verify user identity | Control user access rights |
| When it happens | Before accessing API | After authentication, during data access |
| Common methods | JWT tokens, OAuth, sessions | Role checks, permission flags |
| Focus | Who you are | What you can do |
| GraphQL role | Validate user token in context | Check user permissions in resolvers |
| Failure result | Reject request or ask to login | Deny access to specific fields or mutations |
Key Differences
Authentication is the process of confirming a user's identity. In GraphQL, this usually means checking a token sent in the request headers and adding user info to the request context. Without authentication, the server does not know who is making the request.
Authorization happens after authentication. It decides if the authenticated user has permission to perform certain actions or access specific data. This is often done inside GraphQL resolvers by checking user roles or permissions stored in the context.
In short, authentication answers "Who are you?" and authorization answers "Are you allowed to do this?" Both are essential for secure GraphQL APIs but serve different roles in the request lifecycle.
Code Comparison
Example of authentication in a GraphQL server using JWT token verification to identify the user.
const { ApolloServer, gql } = require('apollo-server'); const jwt = require('jsonwebtoken'); const typeDefs = gql` type Query { me: User } type User { id: ID! name: String! } `; const users = [{ id: '1', name: 'Alice' }]; const getUser = (token) => { try { if (!token) return null; return jwt.verify(token, 'secretkey'); } catch (e) { return null; } }; const resolvers = { Query: { me: (parent, args, context) => { return users.find(u => u.id === context.user?.id) || null; } } }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization || ''; const user = getUser(token.replace('Bearer ', '')); return { user }; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Authorization Equivalent
Example of authorization in GraphQL by checking user roles inside a resolver to allow or deny access.
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 'Sensitive information for admins only'; } } }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // Simulate authenticated user with role const user = { id: '1', name: 'Alice', role: 'user' }; return { user }; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
When to Use Which
Choose authentication when you need to verify the identity of the user making the GraphQL request. This is the first step to secure your API and usually involves validating tokens or credentials.
Choose authorization when you want to control what authenticated users can do or see. Use it inside resolvers to check roles or permissions before returning data or performing actions.
Both are important: authentication protects your API from unknown users, and authorization protects sensitive data from unauthorized access.