Pages that have explicit roles get 403, and my custom JwtAuthenticationConverter is not invoked.
How come?
Im using keycloak as oauth2 provider, and im using oauth2Login in order to prompt login page.
i use the same code that is in the spring docs.
package com.eLoomina.gateway.security
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.convert.converter.Converter
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter
import org.springframework.security.web.server.SecurityWebFilterChain
import reactor.core.publisher.Mono
import java.util.stream.Collectors
@Configuration
@EnableWebFluxSecurity
class SecurityConfig {
companion object {
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val logger = LoggerFactory.getLogger(javaClass.enclosingClass)
}
@Bean
@Throws(Exception::class)
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http.authorizeExchange()
.pathMatchers("/login", "/").permitAll()
.pathMatchers("/login/with-role").hasRole("populate")
.anyExchange().authenticated()
.and()
.oauth2Login().and()
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(grantedAuthoritiesExtractor())
return http.build()
}
fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
val extractor = KeycloakRealmRoleConverter()
return ReactiveJwtAuthenticationConverterAdapter(extractor)
}
class KeycloakRealmRoleConverter : JwtAuthenticationConverter() {
override fun extractAuthorities(jwt: Jwt): Collection<GrantedAuthority> {
val realmAccess = jwt.claims["realm_access"] as Map<String, Any>
logger.info("code not reached")
return (realmAccess["roles"] as List<String>).stream()
.map { roleName: String -> "ROLE_${roleName.toUpperCase()}" } // prefix to map to a Spring Security "role"
.map { role: String? -> SimpleGrantedAuthority(role) }
.collect(Collectors.toList())
}
}
}
question from:
https://stackoverflow.com/questions/65875067/custom-reactivejwtauthenticationconverteradapter-not-invoked 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…