Spring Boot, OAuth2 authentication is lost between requests

Solution 1:

I found the solution, I hope this could help.

The thing that caused the problem for me was that GCP and GAE use multiple instances of the server, and if the user is logged in a certain instance does not mean the other instances are familiar with it too because the Spring HTTPSession is in-memory.

I Switched the Session platform to use the spring-session jdbc using the following configuration in the application.properties :

spring.session.store-type=jdbc

-- you can use redis instead of jdbc, as long as the session is stored in a shared place among all instances.

also added the transaction manager to the SecurtityConfig:

@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

and added the following configurations :

    http.csrf().disable()
            .sessionManagement()
            .maximumSessions(1)
            .and()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)

In addition like @stringy05 mentioned the authrizenClient Repository needs ti be updated too:

    /**
 * Use the servlet container session store for authorized OAuth2 Clients
 */
@Bean
public OAuth2AuthorizedClientRepository authorizedClientRepository() {
    return new HttpSessionOAuth2AuthorizedClientRepository();
}

and add the .authorizedClientRepository line to the httpconfig:

....
                .oauth2Login()
            .loginPage("/Login")
            .authorizedClientRepository(authorizedClientRepository)
            .authorizationEndpoint().and()
            .userInfoEndpoint()
            .userService(oAuth2UserService)
            .and()
            .successHandler(new OAuth2LoginSuccess())

....

Regarding the GAE, I added the following line to the app.yaml file:

  network:
    session_affinity: true