Метод обработки контроллера несколько раз, когда я добавляю фильтр в цепочку безопасностиJAVA

Программисты JAVA общаются здесь
Anonymous
Метод обработки контроллера несколько раз, когда я добавляю фильтр в цепочку безопасности

Сообщение Anonymous »

Итак, это мой контроллер < /p>

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

@RestController
class SyncRevokedTokensController(private val syncRevokedTokenService: SyncRevokedTokensService) {

private val log: Logger = LoggerFactory.getLogger(SyncRevokedTokensController::class.java)

@PostMapping("/sync-revoked-tokens", consumes = ["application/json"])
fun syncTokens(@RequestBody request: Mono): Mono {
log.info("Received request to sync revoked tokens")

return request
.flatMap { syncRequest ->
if (syncRequest.startSynchronization) {
log.info("Starting sync of revoked tokens")
syncRevokedTokenService.sync()
.doOnSuccess {
log.info("Completed sync service operation")
}
.onErrorResume { error ->
log.error("Error during sync operation", error)
Mono.error(error)
}
} else {
log.info(
"Synchronization not started as startSynchronization is false "
)
Mono.empty()
}
}
.doOnSuccess {
log.info("Successfully completed sync tokens request")
}
.onErrorResume { error ->
log.error("Error processing sync request", error)
Mono.error(error)
}
}
}
< /code>
и на основе журнала он пытается обработать этот метод дважды, в первый раз, когда он обрабатывается правильно, а на втором запуске он бросает это исключение org.springframework.core.codec.decodingexception: без корпуса запроса < /code> и результаты с 400 плохой запросом. < /p>
Это потому, что я добавляю фильтр в цепочке безопасности, которая является той: < /p>
    @Bean
@Order(2)
fun syncRevokedTokensFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.securityMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/sync-revoked-tokens"))
.authorizeExchange { exchanges ->
exchanges.anyExchange().authenticated()
}
.addFilterAt(MfaEndpointsAuthorizationWebFilter(), SecurityWebFiltersOrder.LAST)
.oauth2ResourceServer { oauth2 ->
oauth2
.bearerTokenConverter(ServerBearerTokenAuthenticationConverter())
.authenticationManagerResolver(customAuthenticationOauth2ManagerResolver())
}
.csrf { it.disable() }
.headers { it.disable() }
.build()
}
На случай, если я удаляю эту строку кода: .addfilterat (mfaendpointsAuthorizationWebFilter (), SecurityWebFilterSorder.last) Я получаю 200 от моего API, и это не пробует обработки несколько раз. < /p>
Здесь также фильтр: < /p>

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

class MfaEndpointsAuthorizationWebFilter : WebFilter {

companion object {
private val log = LoggerFactory.getLogger(MfaEndpointsAuthorizationWebFilter::class.java)
}

private fun isMfaScopeSupportedEndpoint(path: String): Boolean {
//TODO on purpose delete logic because of security reasons
return true
}

override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono {
log.info("Starting MfaEndpointsAuthorizationWebFilter for path: {}", exchange.request.path)
return ReactiveSecurityContextHolder.getContext()
.flatMap { securityContext: SecurityContext ->
if (securityContext.authentication is CustomAuthentication) {
val customAuthentication = securityContext.authentication as CustomAuthentication
val scope = customAuthentication.tokenScope

if ("totp_authenticator" == scope && !isMfaScopeSupportedEndpoint(exchange.request.path.value())) {
exchange.response.setStatusCode(HttpStatus.UNAUTHORIZED)
return@flatMap Mono.error(OAuth2AuthenticationException("MFA scope is not supported for called url"))
}
}
chain.filter(exchange)
}
.switchIfEmpty(chain.filter(exchange)) // Proceed with the filter chain if no security context is present
.onErrorResume(OAuth2AuthenticationException::class.java) { _: OAuth2AuthenticationException? -> Mono.empty() }
}
}
Как я уже сказал>

Подробнее здесь: https://stackoverflow.com/questions/794 ... rity-chain

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