I'm working on a spring boot project with an OAuth2 resource server authentication method, the access token is verified on the authorization server.
This application provides also an endpoint to get a token signed by itself.
I would like to provide an authentication backup method with a WebFilter that verify the token signature if OAuth2 method failed like this :
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http.invoke {
csrf { disable() }
authorizeExchange {
authorize("/actuator/**", permitAll)
authorize("/api/login", permitAll)
authorize("/v3/api-docs", permitAll)
authorize("/**", authenticated)
}
oauth2ResourceServer {
jwt {
jwtAuthenticationConverter = oauth2JwtConverter
}
}
addFilterAt(JWTFilter(tokenService), SecurityWebFiltersOrder.AUTHENTICATION)
}
}
My JWTFilter :
class JWTFilter(
private val tokenService: TokenService
) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
return resolveToken(exchange.request)
?.takeIf { tokenService.validateToken(it) }
?.let { tokenService.getAuthentication(it) }
?.let { chain.filter(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(it)) }
?: chain.filter(exchange)
}
private fun resolveToken(request: ServerHttpRequest): String? {
return request.headers[AUTHORIZATION_HEADER]
?.get(0)
?.takeIf { it.startsWith("Bearer ") }
?.substring(7)
}
}
The problem is that the authentication context set by the filter is ignored if OAuth2 failed.
How can i manage that ?