Troubleshooting Spring Boot OAuth2 Integration: Session Issues and Fixes
This guide walks through configuring Spring Boot 2.3.10 with OAuth2 client support, detailing required dependencies, application and security settings, common session‑related errors, step‑by‑step debugging of OAuth2LoginAuthenticationFilter and OAuth2AuthorizationRequestRedirectFilter, and the final solution of aligning hostnames to preserve cookies.
Environment
Spring Boot 2.3.10.RELEASE + OAuth2
Related 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
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: debugExplanation of key properties:
authorization-uri : URL of the authentication service.
token-uri : URL to obtain the token.
user-info-uri : URL to fetch user information.
user-name-attribute : JSON key for the username in the user‑info response.
redirect-uri : Must match the redirect URI configured in the authentication service; {baseUrl} is replaced with the current service address and port.
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()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
}
}Session handling is required because, without it, the session remains empty during source tracing.
Testing the Configuration
Access the test endpoint /home. After login, an error appears because the OAuth2AuthorizationRequest cannot be retrieved from the session.
The root cause is that the OAuth2AuthorizationRequest stored in the session is not found.
Understanding the Filter Flow
The OAuth2LoginAuthenticationFilter processes the callback URL /login/oauth2/code/*. It retrieves the saved OAuth2AuthorizationRequest from the session:
Map<String, OAuth2AuthorizationRequest> authorizationRequests = session == null ? null : (Map<String, OAuth2AuthorizationRequest>) session.getAttribute(this.sessionAttributeName);If the request is missing, the filter cannot proceed.
The request is originally saved by OAuth2AuthorizationRequestRedirectFilter during the first redirect to the authorization server.
public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter {
public static final String DEFAULT_AUTHORIZATION_REQUEST_BASE_URI = "/oauth2/authorization";
}During testing, it was observed that the session content disappears after the user is redirected to the authentication service, indicating that cookies are not shared across different ports (e.g., localhost:8080 vs localhost:8081).
Solution
Modify the hosts file to map a custom domain (e.g., www.xg.com) to 127.0.0.1, and update the application configuration to use this domain for all OAuth2 URLs. This ensures that the same cookie is used for both the client and the authentication service.
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 applying the domain change, the flow works: the client obtains an authorization code, exchanges it for a token, retrieves user information, and the AuthenticationManager logs the user in.
Additional Notes
When calling the user‑info endpoint, only validate the token; do not apply additional security filters.
Example controller for the user‑info endpoint:
@GetMapping("/userinfo")
public Map<String, Object> userinfo(){
Map<String, Object> res = new HashMap<>();
String token = extractToken();
OAuth2Authentication auth = tokenService.loadAuthentication(token);
res.put("name", auth.getName());
return res;
}The core filters involved in third‑party OAuth2 integration are OAuth2AuthorizationRequestRedirectFilter and OAuth2LoginAuthenticationFilter.
All steps completed successfully.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
