Part 5: Authentication and Authorization
Knowing Who Is Calling and What They Can Do
JWT in the Apollo Context
// src/auth.ts
import * as jose from 'jose';
export interface AuthUser {
id: string;
email: string;
role: 'ADMIN' | 'EDITOR' | 'VIEWER';
}
const SECRET = new TextEncoder().encode(
process.env.JWT_SECRET ?? 'change-this-secret-in-production',
);
export async function verifyToken(token: string): Promise<AuthUser> {
const { payload } = await jose.jwtVerify(token, SECRET, {
algorithms: ['HS256'],
});
return {
id: payload.sub as string,
email: payload.email as string,
role: payload.role as AuthUser['role'],
};
}
export function extractBearerToken(authHeader: string | undefined): string | null {
if (!authHeader?.startsWith('Bearer ')) return null;
return authHeader.slice(7);
}Field-Level Authorization: Resolver Guards
Schema Directive Approach
Protecting Subscriptions
JWT Signing Utility
Python Strawberry: Auth with Permissions
Authorization Summary
Pattern
TypeScript
Python
What's Next
PreviousPart 4: GraphQL Client Development — TypeScript and PythonNextPart 6: GraphQL Federation — TypeScript Gateway and Python Subgraph
Last updated