I have a Spring Boot backend that uses the spring-boot-starter-oauth2-client in order to have a google oauth2 login system for my site.
Here is the SecurityFilterChain, when a user signs in with google, it adds the user to my database. GoogleOAuth2 user is a custom OAuth2User i made that exposes attributes like “email” more easily.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/oauth/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2Login -> oauth2Login
.userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint
.userService(googleOAuth2UserService)
)
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
GoogleOAuth2User googleOAuth2User = (GoogleOAuth2User) authentication.getPrincipal();
userService.processOAuthPostLogin(googleOAuth2User);
response.sendRedirect("http://localhost:3000");
}
})
);
return http.build();
}
I then have an endpoint that my authenticated client calls to check if it is signed in
@GetMapping(path = "/authenticated")
public User getAuthenticatedUser(@AuthenticationPrincipal GoogleOAuth2User principal) {
return userService.getAuthenticatedUser(principal);
}
On the frontend, I have a button that goes to the google oauth2 page.
<div>
With Google: <a href="http://localhost:8080/oauth2/authorization/google">click here</a>
</div>
However, the problem I have here is that the client is only authenticated in the current browser session. When I close the browser and reopen it, the client is once again signed out and not authenticated. How do I persist the session so that my user is still “logged in” even after the browser closes?