JAVAPROGLIB Telegram 7095
🔥 Как подключить Keycloak к Spring Boot проекту

Keycloak — это современный open-source Identity Provider от Red Hat, который часто используется в enterprise-проектах для SSO (Single Sign-On), OAuth2 и OpenID Connect. Ниже — пошаговая настройка интеграции Keycloak с Spring Boot 3 и Spring Security 6.

1️⃣ Зависимости

Проверьте, что в проекте есть или добавьте следующие зависимости:

— Spring Web
— Spring Security
— OAuth2 Resource Server
— OAuth2 Client

2️⃣ Разворачиваем Keycloak

Запустите Keycloak через Docker:
docker run -d \
-p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:25.0.2 start-dev


После запуска откройте http://localhost:8080, войдите под admin/admin и создайте realm, например demo-realm.

3️⃣ Настройка клиента в Keycloak

В разделе Clients → Create client укажите:

— Client ID: spring-client
— Client Protocol: openid-connect
— Root URL: http://localhost:8081

В разделе Settings:

— Установите Access Type → confidential
— Включите Standard Flow Enabled
— Укажите Redirect URI: http://localhost:8081/login/oauth2/code/keycloak

Сохраните и перейдите на вкладку Credentials — скопируйте Client Secret.

4️⃣ Настройка application.yml

server:
port: 8081

spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: spring-client
client-secret: YOUR_CLIENT_SECRET
scope: openid, profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
keycloak:
issuer-uri: http://localhost:8080/realms/demo-realm


5️⃣ Конфигурация безопасности

Настройте SecurityConfig.java:

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/public").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
);
return http.build();
}
}


🧠 Зачем это нужно:

Keycloak снимает с вас головную боль по хранению паролей, управлению ролями и сессиями. Он интегрируется с LDAP, AD, SAML и десятками внешних OAuth-провайдеров.

🐸 Библиотека джависта

#Enterprise
Please open Telegram to view this post
VIEW IN TELEGRAM
👍92🔥1



tgoop.com/javaproglib/7095
Create:
Last Update:

🔥 Как подключить Keycloak к Spring Boot проекту

Keycloak — это современный open-source Identity Provider от Red Hat, который часто используется в enterprise-проектах для SSO (Single Sign-On), OAuth2 и OpenID Connect. Ниже — пошаговая настройка интеграции Keycloak с Spring Boot 3 и Spring Security 6.

1️⃣ Зависимости

Проверьте, что в проекте есть или добавьте следующие зависимости:

— Spring Web
— Spring Security
— OAuth2 Resource Server
— OAuth2 Client

2️⃣ Разворачиваем Keycloak

Запустите Keycloak через Docker:

docker run -d \
-p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:25.0.2 start-dev


После запуска откройте http://localhost:8080, войдите под admin/admin и создайте realm, например demo-realm.

3️⃣ Настройка клиента в Keycloak

В разделе Clients → Create client укажите:

— Client ID: spring-client
— Client Protocol: openid-connect
— Root URL: http://localhost:8081

В разделе Settings:

— Установите Access Type → confidential
— Включите Standard Flow Enabled
— Укажите Redirect URI: http://localhost:8081/login/oauth2/code/keycloak

Сохраните и перейдите на вкладку Credentials — скопируйте Client Secret.

4️⃣ Настройка application.yml

server:
port: 8081

spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: spring-client
client-secret: YOUR_CLIENT_SECRET
scope: openid, profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
keycloak:
issuer-uri: http://localhost:8080/realms/demo-realm


5️⃣ Конфигурация безопасности

Настройте SecurityConfig.java:

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/public").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
);
return http.build();
}
}


🧠 Зачем это нужно:

Keycloak снимает с вас головную боль по хранению паролей, управлению ролями и сессиями. Он интегрируется с LDAP, AD, SAML и десятками внешних OAuth-провайдеров.

🐸 Библиотека джависта

#Enterprise

BY Библиотека джависта | Java, Spring, Maven, Hibernate


Share with your friend now:
tgoop.com/javaproglib/7095

View MORE
Open in Telegram


Telegram News

Date: |

How to build a private or public channel on Telegram? Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. Co-founder of NFT renting protocol Rentable World emiliano.eth shared the group Tuesday morning on Twitter, calling out the "degenerate" community, or crypto obsessives that engage in high-risk trading. To delete a channel with over 1,000 subscribers, you need to contact user support The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers.
from us


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM American