Как настроить Poursboot и Keycloak Pod в Kubernetes для успешного потока аутентификации?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Как настроить Poursboot и Keycloak Pod в Kubernetes для успешного потока аутентификации?

Сообщение Anonymous »

Я хочу настроить приложение Springboot Thymeleaf вместе с KeyCloak в пространстве имен Kubernetes, которое работает на моем локальном компьютере. По тому, как приложение Springboot работает в своем собственном приложении Pod и KeyCloak на своем собственном стручке, и они общаются друг с другом, чтобы аутентифицировать пользователей и т. Д. Я не знаю, как правильно настроить Springboot с KeyCloak в моем локальном кластере K8, чтобы они могли успешно общаться друг с другом. pom.xml

Код: Выделить всё

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

org.springframework.boot
spring-boot-starter-parent
3.4.1
  

pl.jacekhorabik
urlshortener
0.0.1-SNAPSHOT
urlshortener
urlshortener


21
1.17.1
0.1.3
13.0
4.27.0
25.0.3





org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-data-jpa


org.springframework.boot
spring-boot-starter-security


org.springframework.boot
spring-boot-starter-thymeleaf


org.springframework.boot
spring-boot-starter-actuator


org.springframework.boot
spring-boot-starter-oauth2-client


org.keycloak
keycloak-spring-boot-starter
${org.keycloak.keycloak-spring-boot-starter.version}



org.springframework.boot
spring-boot-starter-test
test


org.springframework.security
spring-security-test
test



org.liquibase
liquibase-core


com.h2database
h2
test


com.mysql
mysql-connector-j
runtime



org.thymeleaf.extras
thymeleaf-extras-springsecurity6



commons-codec
commons-codec
${commons-codec.commons-codec.version}


io.seruco.encoding
base62
${io.seruco.encoding.base62.version}



org.projectlombok
lombok


org.jetbrains
annotations
${org.jetbrains.annotations.version}
compile




< /code>

 Моя конфигурация Spring Security в Application.yml < /code>: < /li>
< /ol>
spring:
security:
oauth2:
client:
provider:
urlshortener-keycloak-provider:
issuer-uri: http://urlshortener-keycloak-service.urlshortener-dev:8080/realms/urlshortener-keycloak-realm
registration:
keycloak:
provider: urlshortener-keycloak-provider
authorization-grant-type: authorization_code
client-id: urlshortener-keycloak-client
client-secret: secret
scope: openid
< /code>

 my securityconfig.java < /code> class: < /li>
< /ol>
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
class SecurityConfig {

@Bean
SecurityFilterChain clientSecurityFilterChain(
@NotNull HttpSecurity http, ClientRegistrationRepository clientRegistrationRepository)
throws Exception {
http.oauth2Login(
login -> {
login.defaultSuccessUrl("/v1/");
});
http.logout(
logout -> {
final var logoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}/v1/");
logout.logoutSuccessHandler(logoutSuccessHandler);
});

http.authorizeHttpRequests(
requests -> {
requests.requestMatchers("/v1/**", "/actuator/health", "/favicon.ico").permitAll();
requests.requestMatchers("/admin").hasAuthority("ADMIN");
requests.requestMatchers("/user").hasAuthority("USER");
requests.anyRequest().denyAll();
});
return http.build();
}
}
< /code>

 Изображение Docker KeyCloak I Impoor, с моим собственным импортом сферы: < /li>
< /ol>
FROM quay.io/keycloak/keycloak:25.0.1

EXPOSE 8080/tcp

ENV KEYCLOAK_ADMIN="admin"
ENV KEYCLOAK_ADMIN_PASSWORD="admin"

ADD ./realm/urlshortener-keycloak-realm.json /opt/keycloak/data/import/

CMD [ "start", \
"--verbose", \
"--features", "hostname:v2", \
"--http-port", "8080", \
"--hostname" , "localhost", \
"--hostname-debug", "true", \
"--http-relative-path", "/", \
"--http-enabled", "true", \
"--health-enabled", "true", \
"--metrics-enabled", "true", \
"--import-realm", \
"--db", "mysql", \
"--db-username", "keycloak-admin", \
"--db-password", "password", \
"--db-url-host", "urlshortener-db-service.urlshortener-dev", \
"--db-schema", "keycloak", \
"--db-url-port", "3306"  \
]
< /code>
Теперь ресурсы K8S: < /p>

 C8s пространство имен, развертывание и обслуживание и обслуживание и обслуживание Keycloak: < /li>
< /ol>
apiVersion: v1
kind: Namespace
metadata:
name: urlshortener-dev

---

apiVersion: apps/v1
kind: Deployment
metadata:
name: urlshortener-backend-deployment
labels:
app: urlshortener
layer: backend
namespace: urlshortener-dev
spec:
template:
metadata:
name: urlshortener-backend-pod
labels:
app: urlshortener
layer: backend
spec:
containers:
- image: urlshortener-backend:latest
name: urlshortener-backend-container
ports:
- containerPort: 8080
imagePullPolicy: IfNotPresent
replicas: 1
selector:
matchLabels:
app: urlshortener
layer: backend
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1

---

apiVersion: v1
kind: Service
metadata:
name: urlshortener-backend-service
namespace: urlshortener-dev
labels:
app: urlshortener
layer: backend
spec:
ports:
- port: 8080
protocol: TCP
targetPort: 8080
nodePort: 30008
selector:
app: urlshortener
layer: backend
type: NodePort

---

apiVersion: apps/v1
kind: Deployment
metadata:
name: urlshortener-keycloak-deployment
labels:
app: urlshortener
layer: keycloak
namespace: urlshortener-dev
spec:
template:
metadata:
name: urlshortener-backend-pod
labels:
app: urlshortener
layer: keycloak
spec:
containers:
- image: urlshortener-keycloak:latest
name: urlshortener-keycloak-container
ports:
- containerPort: 8080
imagePullPolicy: IfNotPresent
replicas: 1
selector:
matchLabels:
app: urlshortener
layer: keycloak
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1

---

apiVersion: v1
kind: Service
metadata:
name: urlshortener-keycloak-service
namespace: urlshortener-dev
labels:
app: urlshortener
layer: keycloak
spec:
ports:
- protocol: TCP
port: 8080
targetPort: 8080
nodePort: 30009
selector:
app: urlshortener
layer: keycloak
type: NodePort

Как видите, у меня также есть MySQL DB, развернутый в этом пространстве имен K8, но в контексте этой проблемы не имеет значения. Настройка K8S Пожалуйста, запустите ./k8s-run.sh в корне репо.

Код: Выделить всё

urlshortener-backend-deployment
):

Код: Выделить всё

Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]:
Factory method 'clientRegistrationRepository' threw exception with message:
The Issuer "http://localhost:8080/realms/urlshortener-keycloak-realm"
provided in the configuration metadata did not match the requested issuer
"http://urlshortener-keycloak-service.urlshortener-dev:8080/realms/urlshortener-keycloak-realm"
Как я могу настроить правильный URL -адрес keycloak в приложении Springboot, чтобы он мог общаться с Pod KeyCloak и перенаправить пользователей для входа в систему с помощью консоли KeyCloak и после успешного входа в систему перенаправить на Springboot?

Подробнее здесь: https://stackoverflow.com/questions/795 ... ful-authen
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Проблемы разрешения Pod Pod Pod Pod DNS
    Anonymous » » в форуме Linux
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • Watch Pod, содержащий несколько контейнеров, использующих метод потока Kubernetes.
    Anonymous » » в форуме Python
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • Pod install -bash: pod: команда не найдена
    Anonymous » » в форуме IOS
    0 Ответы
    68 Просмотры
    Последнее сообщение Anonymous
  • Pod install -bash: pod: команда не найдена
    Anonymous » » в форуме IOS
    0 Ответы
    54 Просмотры
    Последнее сообщение Anonymous
  • Файлы разработки POD исчезают после запуска установки POD?
    Anonymous » » в форуме IOS
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»