Fixing Spring Boot OAuth2 Session Errors: A Complete Walkthrough

This guide explains how to integrate OAuth2 with Spring Boot 2.3.10, troubleshoot missing OAuth2AuthorizationRequest in the session, and resolve the issue by adjusting host configuration and domain settings, providing full code snippets and configuration details.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Fixing Spring Boot OAuth2 Session Errors: A Complete Walkthrough

Environment

Spring Boot 2.3.10.RELEASE with OAuth2.

Dependencies

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Application Configuration (application.yml)

server:
  servlet:
    session:
      timeout: 30m
---
spring:
  security:
    oauth2:
      client:
        provider:
          xgpack:
            authorization-uri: http://localhost:8208/oauth/authorize
            token-uri: http://localhost:8208/oauth/token
            user-info-uri: http://localhost:8208/users/userinfo
            user-name-attribute: name
        registration:
          auth2:
            provider: xgpack
            client-id: 1
            client-secret: 1
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
---
logging:
  level:
    org.springframework.security: debug

Explanation of fields: authorization-uri points to the authentication service, token-uri obtains the token, user-info-uri fetches user details, user-name-attribute specifies the JSON key for the username, and redirect-uri must match the one configured in the authentication service.

Security Configuration

@Configuration
public class OAuthConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
            .antMatchers("/error", "/webjars/**", "/resources/**", "/index/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login()
            .logout();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    }
}

Session is forced to be created because without it the OAuth2AuthorizationRequest stored in the session cannot be retrieved.

Root Cause Analysis

The error occurs because the session does not contain the saved OAuth2AuthorizationRequest. The filter OAuth2LoginAuthenticationFilter tries to read it with:

Map<String, OAuth2AuthorizationRequest> authorizationRequests =
    session == null ? null : (Map<String, OAuth2AuthorizationRequest>)
    session.getAttribute(this.sessionAttributeName);

The request is actually stored by OAuth2AuthorizationRequestRedirectFilter during the first redirect to the authorization endpoint.

Two redirects happen: the first to /oauth2/authorization where the request is saved to the session, and the second back to the application after authentication.

Solution

Modify the hosts file to map a custom domain (e.g., www.xg.com) to 127.0.0.1, then update the OAuth2 provider URLs to use this domain. This prevents cookie separation between localhost:8080 and localhost:8081, ensuring the session is shared.

spring:
  security:
    oauth2:
      client:
        provider:
          xgpack:
            authorization-uri: http://www.xg.com:8208/oauth/authorize
            token-uri: http://www.xg.com:8208/oauth/token
            user-info-uri: http://www.xg.com:8208/users/userinfo
            user-name-attribute: name
        registration:
          auth2:
            provider: xgpack
            client-id: 1
            client-secret: 1
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'

After this change, the flow works: the application obtains the authorization code, exchanges it for a token, calls the user‑info endpoint, and the user is authenticated.

Final Flow

Redirect to the authorization server.

Authorization server redirects back with a code. OAuth2LoginAuthenticationProvider exchanges the code for a token.

Token is used to call the user‑info endpoint.

User details are passed to AuthenticationManager for login.

Make sure the user‑info endpoint is excluded from security filters, as it only needs token validation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConfigurationSpring BootSecurityOAuth2Session
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.