Swagger + Keycloak Integration Cheat Sheet
Purpose of @SecurityScheme
The @SecurityScheme annotation is part of the Swagger/OpenAPI integration used with Springdoc. It tells Swagger
how the API is secured and enables the Swagger UI to support OAuth2 JWT Bearer authentication.
Sample Annotation
@SecurityScheme(
name = "keycloak",
type = SecuritySchemeType.OAUTH2,
bearerFormat = "JWT",
scheme = "bearer",
in = SecuritySchemeIn.HEADER,
flows = @OAuthFlows(
password = @OAuthFlow(
authorizationUrl = "http://localhost:9090/realms/chit-chat-hub/protocol/openid-connect/auth",
tokenUrl = "http://localhost:9090/realms/chit-chat-hub/protocol/openid-connect/token"
Explanation of Parameters
- name: The name used to refer to the scheme in @SecurityRequirement
- type: The type of security (OAUTH2 in this case)
- scheme: The security scheme used ("bearer" for JWT)
- bearerFormat: The format of the bearer token ("JWT")
- in: Location of the token ("HEADER")
- flows: Defines the OAuth2 flow used (password grant here)
- tokenUrl: The URL where Swagger fetches the token from Keycloak
Swagger + Keycloak Integration Cheat Sheet
- authorizationUrl: Required in some tools, not used in password flow but often needed
Apply Security to Controllers
Use the @SecurityRequirement annotation on your controllers or methods:
@SecurityRequirement(name = "keycloak")
@RestController
@RequestMapping("/api")
public class MessageController {
...
Testing in Swagger UI
1. Open Swagger UI
2. Click "Authorize"
3. Enter Keycloak credentials
4. Swagger retrieves a JWT from Keycloak and sends it in each API request using:
Authorization: Bearer <token>
Summary
@SecurityScheme defines how Swagger understands your API's authentication. With Keycloak and Spring Security, this
enables full OAuth2 JWT integration and secure, testable endpoints via Swagger UI.