Authentication Configuration

Adding authentication information to your OpenAPI specification allows users to authenticate with your API directly from the Swagger UI interface. This page explains how to configure different authentication methods for your Serverpod Swagger documentation.

Adding Authentication to OpenAPI Specification

You can add authentication schemes to your OpenAPI specification by creating a YAML file with security definitions.

Create a file named openapi_security.yaml in your project root:

openapi_security.yaml
1security:
2  - BearerAuth: []
3
4components:
5  securitySchemes:
6    BearerAuth:
7      type: http
8      scheme: bearer
9      bearerFormat: JWT
10      description: Enter your JWT token in the format 'Bearer {token}'

The generator will include these security definitions in the generated OpenAPI specification.

Common Authentication Types

Bearer Token Authentication

openapi_security.yaml
1security:
2  - BearerAuth: []
3
4components:
5  securitySchemes:
6    BearerAuth:
7      type: http
8      scheme: bearer
9      bearerFormat: JWT
10      description: Enter your JWT token in the format 'Bearer {token}'

API Key Authentication

openapi_security.yaml
1security:
2  - ApiKeyAuth: []
3
4components:
5  securitySchemes:
6    ApiKeyAuth:
7      type: apiKey
8      in: header
9      name: X-API-Key
10      description: Enter your API key

Basic Authentication

openapi_security.yaml
1security:
2  - BasicAuth: []
3
4components:
5  securitySchemes:
6    BasicAuth:
7      type: http
8      scheme: basic
9      description: Enter your username and password

OAuth 2.0 Authentication

openapi_security.yaml
1security:
2  - OAuth2: []
3
4components:
5  securitySchemes:
6    OAuth2:
7      type: oauth2
8      flows:
9        implicit:
10          authorizationUrl: https://example.com/oauth/authorize
11          scopes:
12            read: Read access to the API
13            write: Write access to the API

Applying Security to Specific Endpoints

You can apply security requirements to specific endpoints by using the @Security annotation in your endpoint definitions:

example_endpoint.dart
1/// Get user profile
2/// 
3/// Retrieves the profile of the authenticated user
4(['BearerAuth'])
5('/users/profile')
6Future<User> getUserProfile(Session session);
7
8/// List all users
9/// 
10/// Requires admin privileges
11(['BearerAuth', 'ApiKeyAuth'])
12('/users')
13Future<List<User>> listUsers(Session session);

In this example, the getUserProfile endpoint requires Bearer authentication, while the listUsers endpoint requires both Bearer and API Key authentication.

Implementing Authentication in Serverpod

While Swagger UI allows users to provide authentication credentials for testing, you need to implement the actual authentication logic in your Serverpod server.

Bearer Token Authentication Example

authentication_interceptor.dart
1import 'package:serverpod/serverpod.dart';
2import 'package:jwt_decoder/jwt_decoder.dart';
3
4class AuthenticationInterceptor extends Interceptor {
5  
6  Future<bool> beforeHandle(Session session, String methodName) async {
7    // Skip authentication for certain methods
8    if (methodName == 'login' || methodName == 'register') {
9      return true;
10    }
11
12    // Get the authorization header
13    final authHeader = session.request?.headers['authorization'];
14    if (authHeader == null || !authHeader.startsWith('Bearer ')) {
15      session.response.statusCode = 401;
16      session.response.write('Unauthorized');
17      return false;
18    }
19
20    // Extract and validate the token
21    final token = authHeader.substring(7);
22    try {
23      final decodedToken = JwtDecoder.decode(token);
24      
25      // Check if token is expired
26      if (JwtDecoder.isExpired(token)) {
27        session.response.statusCode = 401;
28        session.response.write('Token expired');
29        return false;
30      }
31      
32      // Add user info to session
33      session.auth = decodedToken;
34      return true;
35    } catch (e) {
36      session.response.statusCode = 401;
37      session.response.write('Invalid token');
38      return false;
39    }
40  }
41}
42
43// Register the interceptor in your server setup
44void main() async {
45  final pod = Serverpod(...);
46  
47  // Add the authentication interceptor
48  pod.addInterceptor(AuthenticationInterceptor());
49  
50  await pod.start();
51}

Testing Authentication in Swagger UI

Once you've configured authentication in your OpenAPI specification, users can authenticate in Swagger UI by following these steps:

  1. Click the "Authorize" button at the top of the Swagger UI page
  2. Enter the required credentials for the authentication method
  3. Click "Authorize" to apply the credentials
  4. Close the dialog and test the authenticated endpoints

Tip: You can use the persistAuthorization option in your Swagger UI configuration to make the authorization persist between page refreshes.

Next Steps