Unable to make the oauth2Login as stateless

Viewed 459

I have provided the cookie based authorization request repository to oauth2Login() dsl to make it as stateless. but when I add the session creation policy as STATELESS , the oauth2 login is not working and returning "too many callbacks" error in UI page.

I have used the following oauth2Login config. for login with google oauth2 provider.

    @Autowired
    private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().csrfTokenRepository(new CookieCsrfTokenRepository())
                .ignoringAntMatchers("/oauth2/authorization/google")
                .and()
                .sessionManagement(sessionMgmtConfig -> sessionMgmtConfig.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated())
                .oauth2Login(oauth2Config -> oauth2Config
                        .authorizationEndpoint(config -> config.authorizationRequestRepository(httpCookieOAuth2AuthorizationRequestRepository))
                        .userInfoEndpoint(config -> config.oidcUserService(oidcUserOAuth2UserService()))
                        .successHandler(authenticationSuccessHandler())
                )
                ;//.logout(logoutConfig -> logoutConfig.addLogoutHandler(logoutHandler()))
    }

    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setRequestCache(new CookieRequestCache());

        return successHandler;
    }

If I comment out the session management line, it is working as expected and creating the JSESSION but when not working if I uncomment this part. Am I missing something?

1 Answers

It is not so easy to have oauth2Login and stateless sessionManagement. The problem is that Spring needs to store information about OAuth 2.0 state parameter. Normally it is stored in session but when you disable it, Spring gets crazy ("too many callbacks") because it can not find it.

To solve that problem you can use your own cookie to store state parameter. This can be done by providing a custom implementation of AuthorizationRequestRepository<OAuth2AuthorizationRequest>.

There is a nice blog post descriging everything in more details.

https://www.jessym.com/articles/stateless-oauth2-social-logins-with-spring-boot

What is the purpose of the 'state' parameter in OAuth authorization request

Related