OAuth Keycloak
==============
https://github.com/spring-boot-tutorials/spring-oauth-keycloak
Install & Run Keycloak Server
-----------------------------
Create a keycloak directory
.. code-block:: sh
mkdir keycloak
cd keycloak
Within that directory, create a docker-compose.yml file with the following contents:
.. code-block:: yaml
services:
keycloak:
container_name: baeldung-keycloak.openid-provider
image: quay.io/keycloak/keycloak:25.0.1
command:
- start-dev
- --import-realm
ports:
- 8080:8080
volumes:
- ./keycloak/:/opt/keycloak/data/import/
environment:
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD}
KC_HTTP_PORT: 8080
KC_HOSTNAME_URL: http://localhost:8080
KC_HOSTNAME_ADMIN_URL: http://localhost:8080
KC_HOSTNAME_STRICT_BACKCHANNEL: true
KC_HTTP_RELATIVE_PATH: /
KC_HTTP_ENABLED: true
KC_HEALTH_ENABLED: true
KC_METRICS_ENABLED: true
extra_hosts:
- "host.docker.internal:host-gateway"
healthcheck:
test: ['CMD-SHELL', '[ -f /tmp/HealthCheck.java ] || echo "public class HealthCheck { public static void main(String[] args) throws java.lang.Throwable { System.exit(java.net.HttpURLConnection.HTTP_OK == ((java.net.HttpURLConnection)new java.net.URL(args[0]).openConnection()).getResponseCode() ? 0 : 1); } }" > /tmp/HealthCheck.java && java /tmp/HealthCheck.java http://localhost:8080/auth/health/live']
interval: 5s
timeout: 5s
retries: 20
Run Keycloak server
.. code-block:: sh
export KEYCLOAK_ADMIN_PASSWORD=admin
docker compose up -d
Create Initial Code Base
------------------------
- Go to https://start.spring.io/
- Add the following dependencies:
- spring-boot-starter-oauth2-client
- spring-boot-starter-security
- spring-boot-starter-thymeleaf
- spring-boot-starter-web
- thymeleaf-extras-springsecurity6
- Click ``Generate``
Dependencies
------------
Dependencies used in ``pom.xml``:
.. code-block:: xml
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-oauth2-client
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.thymeleaf.extras
thymeleaf-extras-springsecurity6
Properties
----------
Add the following properties in ``src/main/resources/application.properties``:
.. code-block:: properties
spring.security.oauth2.client.provider.baeldung-keycloak.issuer-uri=http://localhost:8080/realms/baeldung-keycloak
spring.security.oauth2.client.registration.keycloak.provider=baeldung-keycloak
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.client-id=baeldung-keycloak-confidential
spring.security.oauth2.client.registration.keycloak.client-secret=secret
spring.security.oauth2.client.registration.keycloak.scope=openid
Configuration
-------------
Create new file ``src/main/java/com/example/OAuth2/Login/config/AuthoritiesConverter.java``:
.. code-block:: java
public interface AuthoritiesConverter extends Converter