Неверный токен CSRF при вызове микросервисов через мой весенний облачный шлюзJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Неверный токен CSRF при вызове микросервисов через мой весенний облачный шлюз

Сообщение Anonymous »

Я застрял в том, что в моем приложении для микросопервизирования Spring Boot Microservice с помощью Spring Cloud Gateway.
У меня есть микросервис для базы аутентификации на keycloak, обнаруживая некоторые API, такие как регистр, вход в систему и т. Д. Недопустимый токен CSRF, найденной для http: // localhost: 8084/api/1.0/auth/login
Я отключил Cors в моей конфигурации безопасности Spring для каждого из моих двух компонентов (шлюз и микросервис).
Вы можете найти неглубокие элементы, касающиеся запроса Curl, Spress Security и Application yaml. Microservices. < /p>
Итак, с помощью моего Auth Microservice все в порядке, я получаю токен носителя: < /p>
curl --location 'http://localhost:8083/api/1.0/auth/login' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "username",
"password": "password"
}'
< /code>
С шлюзом я получаю http 401: < /p>
curl --location 'http://localhost:8084/api/1.0/auth/login' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "username",
"password": "password"
}'
< /code>
Конфигурация безопасности шлюза: < /p>
package com.omb.ombgateway.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

public class SecurityConfig {

@Bean
public SecurityFilterChain gatewaySecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/1.0/auth/**", "/actuator/**", "/h2-console/**").permitAll()
.requestMatchers("/api/1.0/service1/**", "/api/1.0/service2/**")
.hasAnyRole("USER", "ADMIN").anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}
< /code>
Application.yaml: < /p>
spring:
application:
name: omb-gateway
cloud:
gateway:
routes:
- id: auth-service
uri: lb://auth-service
predicates:
- Path=/api/v1/auth/**
- id: service1
uri: lb://service1
predicates:
- Path=/api/v1/service1/**
- id: service2
uri: lb://service2
predicates:
- Path=/api/v1/service2/**
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/realms/My-Realm
server:
port: 8084
< /code>
Аутентификация Микросервиса Security Confif: < /p>
package com.omb.ombauth.configuration;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/1.0/auth/**", "/actuator/**", "/h2-console/**").permitAll()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
http.cors(Customizer.withDefaults());

return http.build();
}

}
< /code>
Authentication Microservice Application.yaml < /p>
keycloak:
auth-server-url: "http://localhost:8080"
realm: "My-Realm"
resource: "my-client"
public-client: false
credentials:
secret: "my-secret"
spring:
application:
name: "auth-service"
security:
oauth2:
resourceserver:
jwt:
issuer-uri: "http://localhost:8080/realms/My-Realm"
server:
port: 8083

eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
< /code>
Я пытаюсь провести токен аутентификации через мой весенний облачный шлюз, но я всегда получаю ошибку Cors: < /p>
2025-04-07 11:00:18,536 DEBUG [http-nio-8084-exec-1] o.s.s.w.c.CsrfFilter: Invalid CSRF token found for http://localhost:8084/api/1.0/auth/login
2025-04-07 11:00:18,537 DEBUG [http-nio-8084-exec-1] o.s.s.w.a.AccessDeniedHandlerImpl: Responding with 403 status code
2025-04-07 11:00:18,537 TRACE [http-nio-8084-exec-1] o.s.s.w.h.w.HstsHeaderWriter: Not injecting HSTS header since it did not match request to [Is Secure]
2025-04-07 11:00:18,537 TRACE [http-nio-8084-exec-1] o.s.w.f.RequestContextFilter: Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@304513e3
2025-04-07 11:00:18,540 TRACE [http-nio-8084-exec-1] o.s.w.f.RequestContextFilter: Bound request context to thread: org.apache.catalina.core.ApplicationHttpRequest@39d025a8
2025-04-07 11:00:18,544 TRACE [http-nio-8084-exec-1] o.s.w.s.h.AbstractHandlerMethodMapping: 2 matching mappings: [{ [/error]}, { [/error], produces [text/html]}]
2025-04-07 11:00:18,550 TRACE [http-nio-8084-exec-1] o.s.b.f.s.AbstractBeanFactory: Returning cached instance of singleton bean 'basicErrorController'
2025-04-07 11:00:18,551 TRACE [http-nio-8084-exec-1] o.s.s.w.FilterChainProxy: Trying to match request against DefaultSecurityFilterChain defined as 'jwtSecurityFilterChain' in [class path resource [org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration$OAuth2SecurityFilterChainConfiguration.class]] matching [any request] and having filters [DisableEncodeUrl, WebAsyncManagerIntegration, SecurityContextHolder, HeaderWriter, Csrf, Logout, BearerTokenAuthentication, RequestCacheAware, SecurityContextHolderAwareRequest, AnonymousAuthentication, ExceptionTranslation, Authorization] (1/1)
2025-04-07 11:00:18,551 DEBUG [http-nio-8084-exec-1] o.s.s.w.FilterChainProxy: Securing POST /error
< /code>
2025-04-07 11:00:18,557 TRACE [http-nio-8084-exec-1] o.s.s.w.a.ExceptionTranslationFilter: Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=447CB86A957451F263AD98C35EBFC79C], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied
org.springframework.security.authorization.AuthorizationDeniedException: A c c e s s D e n i e d < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a c c e s s . i n t e r c e p t . A u t h o r i z a t i o n F i l t e r . d o F i l t e r ( A u t h o r i z a t i o n F i l t e r . j a v a : 9 9 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a c c e s s . E x c e p t i o n T r a n s l a t i o n F i l t e r . d o F i l t e r ( E x c e p t i o n T r a n s l a t i o n F i l t e r . j a v a : 1 2 6 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a c c e s s . E x c e p t i o n T r a n s l a t i o n F i l t e r . d o F i l t e r ( E x c e p t i o n T r a n s l a t i o n F i l t e r . j a v a : 1 2 0 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a u t h e n t i c a t i o n . A n o n y m o u s A u t h e n t i c a t i o n F i l t e r . d o F i l t e r ( A n o n y m o u s A u t h e n t i c a t i o n F i l t e r . j a v a : 1 0 0 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . s e r v l e t a p i . S e c u r i t y C o n t e x t H o l d e r A w a r e R e q u e s t F i l t e r . d o F i l t e r ( S e c u r i t y C o n t e x t H o l d e r A w a r e R e q u e s t F i l t e r . j a v a : 1 7 9 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . s a v e d r e q u e s t . R e q u e s t C a c h e A w a r e F i l t e r . d o F i l t e r ( R e q u e s t C a c h e A w a r e F i l t e r . j a v a : 6 3 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . w e b . f i l t e r . O n c e P e r R e q u e s t F i l t e r . d o F i l t e r ( O n c e P e r R e q u e s t F i l t e r . j a v a : 1 0 1 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a u t h e n t i c a t i o n . l o g o u t . L o g o u t F i l t e r . d o F i l t e r ( L o g o u t F i l t e r . j a v a : 1 0 7 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . a u t h e n t i c a t i o n . l o g o u t . L o g o u t F i l t e r . d o F i l t e r ( L o g o u t F i l t e r . j a v a : 9 3 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . w e b . f i l t e r . O n c e P e r R e q u e s t F i l t e r . d o F i l t e r ( O n c e P e r R e q u e s t F i l t e r . j a v a : 1 0 1 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . w e b . f i l t e r . O n c e P e r R e q u e s t F i l t e r . d o F i l t e r ( O n c e P e r R e q u e s t F i l t e r . j a v a : 1 0 1 ) < b r / > a t o r g . s p r i n g f r a m e w o r k . s e c u r i t y . w e b . F i l t e r C h a i n P r o x y $ V i r t u a l F i l t e r C h a i n . d o F i l t e r ( F i l t e r C h a i n P r o x y . j a v a : 3 7 4 ) < b r / > a t org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:82)
at org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:69)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:233)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:191)
at org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113)
at org.springframework.web.servlet.handler.HandlerMappingIntrospector.lambda$createCacheFilter$3(HandlerMappingIntrospector.java:243)
at org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113)
at org.springframework.web.filter.CompositeFilter.doFilter(CompositeFilter.java:74)
at org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration$CompositeFilterChainProxy.doFilter(WebMvcSecurityConfiguration.java:238)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:362)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:278)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:633)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:411)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:331)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:268)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:380)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:208)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:397)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:905)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1190)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
at java.base/java.lang.Thread.run(Thread.java:1583)
2025-04-07 11:00:18,561 TRACE [http-nio-8084-exec-1] o.s.s.w.s.HttpSessionRequestCache: Did not save request since it did not match [And [Ant [pattern='/**', GET], Not [Ant [pattern='/**/favicon.*']], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@39d2f5f2, matchingMediaTypes=[application/json], useEquals=false, ignoredMediaTypes=[*/*]]], Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@39d2f5f2, matchingMediaTypes=[multipart/form-data], useEquals=false, ignoredMediaTypes=[*/*]]], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@39d2f5f2, matchingMediaTypes=[text/event-stream], useEquals=false, ignoredMediaTypes=[*/*]]]]]
2025-04-07 11:00:18,562 TRACE [http-nio-8084-exec-1] o.s.w.f.RequestContextFilter: Cleared thread-bound request context: org.apache.catalina.core.ApplicationHttpRequest@39d025a8



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

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Весенний облачный шлюз | Маршрутизация на основе тела запроса
    Anonymous » » в форуме JAVA
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Весенний облачный шлюз
    Anonymous » » в форуме JAVA
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Получение ошибки «Неверный токен CSRF», даже если CSRF отключен
    Гость » » в форуме JAVA
    0 Ответы
    90 Просмотры
    Последнее сообщение Гость
  • Весенний облачный контракт 404 на /привод /здоровье
    Anonymous » » в форуме JAVA
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Облачный шлюз Spring не может найти ресурс службы
    Anonymous » » в форуме JAVA
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous

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