Skip to main content

GraphQL Authentication

The GraphQL endpoint supports authentication via Bearer tokens, similar to the REST API.

How It Works

  1. Extract Token: The GraphQL handler extracts the Authorization header from the HTTP request
  2. Lookup Token: Queries the database to find the matching API token
  3. Create Context: Creates a UserContext with token info and injects it into the GraphQL request
  4. 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:

  1. Ensure you're in a development environment
  2. Open http://localhost:3000/v1/graphiql in your browser
  3. Click "HTTP HEADERS" at the bottom left
  4. Add your authorization header:
{
"Authorization": "Bearer your-token-here"
}
  1. 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/gql endpoint requires authentication via the Authorization header for all queries and mutations
  • The /v1/graphiql IDE is only accessible in development environments (returns 404 in production)
  • The /v1/schema endpoint is publicly accessible in all environments