我尝试在spring-cloud-gateway中使用keycloak身份验证构建身份验证,一切正常,但当尝试获取SecurityContextHolder.getContext().getAuthentication()时,它给出null,我不知道为什么?
这里是我的代码安全配置:
@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();
}
}
而我的控制器,我试图在其中获得数据如下:
@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
}
}
我去了一些stackoverflow的答案,但它是不工作的,根据有一些问题与SecurityConfig类,但我无法得到它。请帮助它。
1条答案
按热度按时间bzzcjhmw1#
在React式应用中,
SecurityContext
包含在ReactiveSecurityContextHolder
中,应使用ReactiveSecurityContextHolder
以React式方式获取Authentication
,如下所示: