This application uses Spring OAuth2 and Keycloak authorization to secure its REST APIs. The mappings from OAuth2 terminology to our implementation are:
- Authorization server: Keycloak server
- Resource server: Metadata Application
- Resource owner: Keycloak users with allowed role
- Client: Application calling Metadata REST APIs
No restrictions are applied on the /
and /swagger-ui.html
endpoints, which can be accessed by anonymous users, for example via http://localhost:8085/ and http://localhost:8085/swagger-ui.html. Among all other endpoints, read-only (GET) operation can be issued by anonymous users and update operations (POST, PUT, PATCH, DELETE) can be performed only by users with the "SERVICE_OPERATOR" role (described below).
- Enter the Keycloak public key value in the
application.properties
file, property security.oauth2.resource.jwt.key-value. It should have a value similar to-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9wxxxxxxxxxxxxxxxxxxxffjZs/D+e9A56XuRJSQ9QIDAQAB\n-----END PUBLIC KEY-----
- This can be obtained from Keycloak Realm settings -> Keys -> Public key, at the right-most column.
- Setup and configure Keycloak server with realm, client, role, mapper and user as described in the official documentation
- Ensure that the following Keycloak settings are configured as described:
- Role "SERVICE_OPERATOR": This role name is mandatory. It could be either client role or realm role.
- User name Mapper: Keycloak returns access token in JWT. The logged in username is returned in claim "preferred_username" in said access token, but Spring Security OAuth2 expects the username in claim "user_name". Hence a mapper to a new claim named "user_name" is required.
- 'Redirect URL' in client settings should point to where the metadata API is running
- Get authorization token from the Keycloak server using Postman (for testing)
- In order to send the token
- 2.1. From Swagger: click the
Authorize
button and enter "Bearer " - 2.2. From a REST client: include header "Authorization" with value "Bearer "
- 2.1. From Swagger: click the