'Set jwk-set-uri for Oauth2 resource server at runtime
I have a spring boot application which is configured as a oauth2ResourceServer in the Spring Security config.
This configuration requires the following entry in the application.properties file:
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8888/auth/realms/devrealm/protocol/openid-connect/certs
so that Spring Security can verify the JWT signatures.
The actual implementation works fine, however, I'm having hard time writing the tests. For my tests I use a test Keycloak instance running in a docker container, started by the relevant test using TestContainers. Since the port of the test keycloak changes all the time I cannot set the jwk-set-uri in advance. The actual jwk-set-uri can only be set once the keycloak container started.
So the question is: How could I set or change the spring.security.oauth2.resourceserver.jwt.jwk-set-uri property at runtime?
Solution 1:[1]
The jwk-set-uri can be configured at runtime in your WebSecurityConfig. This takes precedence over any configuration property.
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwkSetUri("https://idp.example.com/.well-known/jwks.json")
)
);
return http.build();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SimonW |
