Authentication & Authorization
The GraphQL API integrates with next-auth for authentication and implements role-based access control with OAuth scope preparation.
How Authentication Works
- Session-based authentication - The GraphQL context extracts the user session from next-auth cookies
- Automatic context creation - Each request creates a fresh context with user info and authorization helpers
- Resolver-level authorization - Each resolver checks authentication and authorization requirements
Context
Every resolver receives a context object with:
req- The original Next.js requestisAuthenticated- Whether the request is authenticateduser- The authenticated user info (id, email, name, image)session- The raw next-auth sessionhasScope(scope)- Check if user has a specific OAuth scopecanAccessResource(ownerId)- Check if user can access a resource
See apps/web/src/lib/graphql/context.ts for the full implementation.
OAuth Scopes
| Scope | Description |
|---|---|
profile:read | Read user profile data |
profile:write | Create and update user profiles |
organization:read | Read organization data |
organization:write | Create and update organizations |
organization:members:read | Read organization membership |
organization:members:write | Add/remove organization members |
admin | Full administrative access |
Currently, authenticated users receive default scopes. In a future OAuth implementation, scopes will be derived from OAuth tokens.
Scopes are defined in packages/shared-graphql/src/types.ts.
Schema Directive
The @auth directive declaratively specifies authorization requirements on types and fields:
@auth(requires: USER)- Requires authentication@auth(requires: ADMIN)- Requires admin role
Error Handling
Authentication errors throw GraphQL errors with code UNAUTHENTICATED. Authorization errors return response wrappers with error code FORBIDDEN.
Authorization in Resolvers
Use the helper functions from apps/web/src/lib/graphql/common/utils.ts:
requireAuth(context)- Throws if not authenticatedrequireScope(context, scope)- Requires authentication and checks scope
Future OAuth Integration
The authentication system is designed to be extended with OAuth:
- Token-based scopes - OAuth tokens will carry granted scopes
- Scope validation -
context.hasScope()will check token scopes - Directive integration - The
@authdirective will validate scopes - Client credentials - Support for machine-to-machine authentication