Spring Cloud Gateway Oauth2Login Return JWT Token Instead of SESSION Cookie Upon Successful Login

試著忘記壹切 提交于 2021-01-28 10:11:42

问题


sorry in advance if the question is previously asked, but I have not been able to find an answer.

I am trying to setup Spring Cloud Gateway to act as a OAuth2 client to authenticate/login users via a Keycloak Authentication server. I have been able to achieve this using the following code snipet:

Security Config:

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
    
    private final GatewayAuthenticationSuccessHandler gatewayAuthenticationSuccessHandler;
    
    public SecurityConfig(GatewayAuthenticationSuccessHandler gatewayAuthenticationSuccessHandler) {
        this.gatewayAuthenticationSuccessHandler = gatewayAuthenticationSuccessHandler;
    }
    
    @Bean
    public SecurityWebFilterChain securityWebFilterChain(
            ServerHttpSecurity http, 
            ReactiveClientRegistrationRepository clientRegistrationRepository) {
        
        http
            .authorizeExchange()
            .pathMatchers("/ui/**").permitAll()
            .anyExchange().authenticated()
                .and()
            .oauth2Login().authenticationSuccessHandler(gatewayAuthenticationSuccessHandler)
                .and()
            .oauth2ResourceServer().jwt();
          
        http.logout(
                logout ->
                    logout.logoutSuccessHandler(
                        new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository)));
        http.logout().logoutUrl("/logout");
              
        http.csrf().disable();
        http.httpBasic().disable();
        http.formLogin().disable();

        return http.build();
    }
    
}

Auth Success Handler:

@Component
public class GatewayAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {
    
    private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
    
    @Value("${my.frontend_url}")
    private String DEFAULT_LOGIN_SUCCESS_URL;
      
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        URI url = URI.create(DEFAULT_LOGIN_SUCCESS_URL); 
        return this.redirectStrategy.sendRedirect(webFilterExchange.getExchange(), url);
    }

}

With this setup, the gateway app can authenticate the users and obtain a JWT token from the authentication server on behalf of the caller (UI app). Based on my understanding, Spring security then uses spring session to create and feed back a SESSION cookie to the caller. This session cookie can be used for subsequent calls to authenticate the user. The gateway would use the SESSION cookie value to retrieve the associated JWT token from the cache and relays it to the downstream resource servers when proxying requests. I have also setup a token refresh filter to refresh the JWT token on the caller's behalf and a Redis ache to share this session cookie between multiple instances of the gateway.

What I would like to do now is to return the actual JWT token that was retrieved by the gateway back to the caller (instead of a SESSION cookie). In other words I am hoping to make my gateway a little more stateless by using JWT end-to-end (instead of using SESSION cookie for caller --> gateway and then JWT for gateway --> resource servers). Is this even possible with the current state of spring cloud gateway?

PS. I am using spring boot version 2.2.8 and spring cloud version HOXTON.SR6


回答1:


Not sure this can help , but try to add a SessionPolicy as STATELESS to your webfilter chain as shown below , and it should work.

http.sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

Also you could try to override the sessionAuthenticationStrategy with a NullAuthenticatedSessionStrategy if you are extending your config class to WebSecurityConfigurerAdapter.

override fun sessionAuthenticationStrategy(): SessionAuthenticationStrategy {
    return NullAuthenticatedSessionStrategy()
}


来源:https://stackoverflow.com/questions/62904118/spring-cloud-gateway-oauth2login-return-jwt-token-instead-of-session-cookie-upon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!