Search code examples
javaspring-securitygoogle-oauth

In Spring Boot/Security + Google oAuth2, how do I determine if a user is already authenticated?


Background:

I've successfully added Google authentication to my website. There's a Login button that works (and stores the user from the db into the session) as well as a Logout button that logs out the user from my application, but obviously not from Google also. There's a menu item that reflects that authentication by only displaying the appropriate Login or Logout menu item, plus access to a Profile page if they're authenticated. In my SecurityConfig.filterChain() method, I have

 .antMatchers("/secure/**").authenticated()

to ensure users can't get into the secure part of the site (ex: secure/xyz) without being authenticated.

Problem:

However, when a user returns to my website (with a new session) and is still logged into Google, my application thinks the user is authenticated and allows access to the secure URLs, via the browser address bar (ex: secure/xyz), without having to log in again.

I want to know if a user is authenticated when they return to the site, at the very least for UI purposes (displaying Login or Logout). Storing the User in the session is insufficient. I assume I need a SessionListener or a HttpSessionIdListener for this, but I'm not sure what code to put in the sessionCreated() or sessionIdChanged() method to get the identity of the authenticated user. What code do I need?


Solution

  • Well, the actual solution show that I'm still learning. When the user returns back to the site, they are not already authenticated. I thought they were only because I had things in SecurityConfig.filterChain() in the wrong order. Once I put

    .antMatchers("/secure/**").authenticated()
    

    at the beginning, everything started working as expected.