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: |

On Tuesday, some local media outlets included Sing Tao Daily cited sources as saying the Hong Kong government was considering restricting access to Telegram. Privacy Commissioner for Personal Data Ada Chung told to the Legislative Council on Monday that government officials, police and lawmakers remain the targets of “doxxing” despite a privacy law amendment last year that criminalised the malicious disclosure of personal information. ‘Ban’ on Telegram Hui said the messages, which included urging the disruption of airport operations, were attempts to incite followers to make use of poisonous, corrosive or flammable substances to vandalize police vehicles, and also called on others to make weapons to harm police. ZDNET RECOMMENDS There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”.
from us


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