java 为什么SecurityContextHolder.getContext().getAuthentication()返回空值?

tp5buhyn  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(309)

我尝试在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类,但我无法得到它。请帮助它。

bzzcjhmw

bzzcjhmw1#

在React式应用中,SecurityContext包含在ReactiveSecurityContextHolder中,应使用ReactiveSecurityContextHolder以React式方式获取Authentication,如下所示:

Mono<Authentication> getAuthentication() {
    return ReactiveSecurityContextHolder.getContext()
            .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty!")))
            .map(SecurityContext::getAuthentication);
}

相关问题