Reputation: 660
I am trying to build authentication in spring-cloud-gateway using keycloak authentication and everything is working but when trying to get SecurityContextHolder.getContext().getAuthentication() it is giving null I am not sure why?
Here it the my code Security Config:
@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveClientRegistrationRepository clientRegistrationRepository) {
// Authenticate through configured OpenID Provider
http.authorizeExchange()
.pathMatchers("/app/**").authenticated().and().oauth2Login();
// Also logout at the OpenID Connect provider
http.logout(logout -> logout.logoutSuccessHandler(
new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository)));
// Require authentication for all requests
http.authorizeExchange().anyExchange().authenticated();
// Allow showing /home within a frame
http.headers().frameOptions().mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN);
// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
http.csrf().disable();
return http.build();
}
}
And my controller in which I am trying to get data is as below:
@RestController
@RequestMapping("/app")
public class UserController {
@Autowired
DataSource dataSource;
@PostMapping(path = "/authenticate", produces = MediaType.APPLICATION_JSON_VALUE)
public String getAuth(@RequestBody Map<String, Object> data) {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
//But it is always null
}
}
I gone few stackoverflow answer but it is not working according to that there is some issue with SecurityConfig class but I am not able to get it. Please help on it.
Upvotes: 0
Views: 757
Reputation: 5095
In reactive applications, SecurityContext
is contained in ReactiveSecurityContextHolder
which should be used to get Authentication
in a reactive way as shown below:
Mono<Authentication> getAuthentication() {
return ReactiveSecurityContextHolder.getContext()
.switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty!")))
.map(SecurityContext::getAuthentication);
}
Upvotes: 2