0
0
GraphqlComparisonBeginner · 4 min read

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.

FactorAuthenticationAuthorization
PurposeVerify user identityControl user access rights
When it happensBefore accessing APIAfter authentication, during data access
Common methodsJWT tokens, OAuth, sessionsRole checks, permission flags
FocusWho you areWhat you can do
GraphQL roleValidate user token in contextCheck user permissions in resolvers
Failure resultReject request or ask to loginDeny 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.

javascript
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}`);
});
Output
Server ready at http://localhost:4000/
↔️

Authorization Equivalent

Example of authorization in GraphQL by checking user roles inside a resolver to allow or deny access.

javascript
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}`);
});
Output
Server ready at http://localhost:4000/
🎯

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.

Key Takeaways

Authentication verifies who the user is by checking identity tokens in GraphQL context.
Authorization controls what an authenticated user can access or do within GraphQL resolvers.
Authentication happens before authorization in the request flow.
Use authentication to secure your API entry point and authorization to protect specific data or actions.
Both are essential for building secure GraphQL APIs.