How does Spring Security handle Oauth2 clients?
search cancel

How does Spring Security handle Oauth2 clients?

book

Article ID: 417594

calendar_today

Updated On:

Products

VMware Tanzu Spring Runtime

Issue/Introduction

Customer upgraded from Spring Security 5.6.9 to 5.8.21 and they want to know how the OAuth2 client (specifically DefaultOAuth2UserService) constructs HTTP requests.

Resolution

DefaultOAuth2UserService  is part of the package  org.springframework.spring.security.oauth2.client

Spring Security's DefaultOAuth2UserService does not create cookies by default. This class is responsible for mapping the user information received from an OAuth2 provider into a Spring Security OAuth2User object, but it does not handle the creation or management of HTTP cookies for authentication state.

The default behavior of Spring Security, particularly when using OAuth2 login flows, typically relies on session-based authentication, which results in the creation of a JSESSIONID cookie to maintain the session state on the server side. However, this is managed by the session management components of Spring Security, not by DefaultOAuth2UserService.

If you need to implement cookie-based authentication (e.g., storing an access token in a cookie), you must explicitly configure this behavior. For example, you can create a custom filter to extract the token from the OAuth2 authorization response and set it as an HTTP-only cookie, or use a custom SessionAuthenticationStrategy to add cookies during authentication. Some implementations also involve creating a custom OAuth2AuthorizedClientService and using a controller to set a session cookie after successful authentication.

DefaultOAuth2UserService focuses solely on user information processing and does not handle cookie creation; any cookie-based authentication mechanism must be implemented separately.

It is important to note that cookies are not automatically forwarded by Spring Security or the underlying HTTP client libraries. The responsibility lies with the application to explicitly manage and forward them. Additionally, security considerations such as the HttpOnly and Secure flags should be respected when forwarding cookies, especially in production environments. For instance, HttpOnly cookies should not be accessible via JavaScript, and Secure cookies should only be sent over HTTPS connections.

To forward cookies from an incoming HttpServletRequest to backend services in Spring Security 5.8, you must manually extract the cookies from the request and include them in the outgoing request, either through a custom filter or by configuring your HTTP client or gateway appropriately.

Spring Security 5.8.21 DID NOT introduce any changes to how the OAuth2 client (specifically DefaultOAuth2UserService) constructs HTTP requests.

This has to be explicitly configured on the application. The issue appears to be application-related. We recommend that customers review how forwarded cookies are created.