GraphQL Authentication
The GraphQL endpoint supports authentication via Bearer tokens, similar to the REST API.
How It Works
- Extract Token: The GraphQL handler extracts the
Authorizationheader from the HTTP request - Lookup Token: Queries the database to find the matching API token
- Create Context: Creates a
UserContextwith token info and injects it into the GraphQL request - Access in Resolvers: GraphQL resolvers can access the user context via
ctx.data::<UserContext>()
Testing Authentication
1. Query Without Authentication
query {
health
currentGps {
id
latitude
longitude
}
}
2. Query With Authentication (using the me query)
Request Headers:
Authorization: Bearer your-token-here
GraphQL Query:
query {
me {
tokenId
description
role
isAdmin
}
currentGps {
id
latitude
longitude
}
}
Response:
{
"data": {
"me": {
"tokenId": "123e4567-e89b-12d3-a456-426614174000",
"description": "Admin Token",
"role": "ADMIN",
"isAdmin": true
},
"currentGps": {
"id": "...",
"latitude": 51.5074,
"longitude": -0.1278
}
}
}
Using GraphiQL
Access the interactive GraphiQL IDE in development environment only:
Development: http://localhost:3000/v1/graphiql
Development Only
GraphiQL is only accessible when APP_ENV is not set to production. In production environments, the endpoint returns a 404 error for security reasons.
To test authenticated queries in GraphiQL:
- Ensure you're in a development environment
- Open http://localhost:3000/v1/graphiql in your browser
- Click "HTTP HEADERS" at the bottom left
- Add your authorization header:
{
"Authorization": "Bearer your-token-here"
}
- Run queries that require authentication
GraphQL Routes
The GraphQL endpoints are available at:
POST /v1/gql- GraphQL endpoint (requires authentication)GET /v1/gql- GraphQL endpoint (requires authentication)GET /v1/graphiql- GraphiQL interactive IDE (development only, no auth required)GET /v1/schema- GraphQL schema in SDL format (no auth required)
Authentication requirements:
- The
/v1/gqlendpoint requires authentication via the Authorization header for all queries and mutations - The
/v1/graphiqlIDE is only accessible in development environments (returns 404 in production) - The
/v1/schemaendpoint is publicly accessible in all environments