skip to Main Content

I am building a web and mobile app with react/react native for front end, Java-spring boot for backend with OAuth2 authorization.
Google OAuth Login from the react web app works fine. How do I manage login sessions and invalidate them on logout.

Any suggestions/advice will be helpful.
Thanks in advance.

Haven’t really tried anything yet; want to understand how this needs to be done so I can check for the same on the mobile app as well.

2

Answers


  1. Reference to spring security

    Here I am trying to post skeleton that can be improved upon as per your project requirements.
    Spring Security Config

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .loginPage("/oauth2/authorization/google")
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("USER");
        }
    }
    
    
    

    RestController to expose login/logout endpoints

    @RestController
    @RequestMapping("/auth")
    public class AuthController {
    
        @PostMapping("/logout")
        public ResponseEntity<?> logout(HttpServletRequest request, HttpServletResponse response) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                new SecurityContextLogoutHandler().logout(request, response, auth);
            }
            return ResponseEntity.ok(new LogoutResponse("Logout successful"));
        }
    
        public static class LogoutResponse {
            private String message;
    
            public LogoutResponse(String message) {
                this.message = message;
            }
    
            public String getMessage() {
                return message;
            }
    
            public void setMessage(String message) {
                this.message = message;
            }
        }
    }
    
    

    properties file

    spring.security.oauth2.client.registration.google.client-id=your-client-id
    spring.security.oauth2.client.registration.google.client-secret=your-client-secret
    spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/google
    spring.security.oauth2.client.registration.google.scope=openid,profile,email
    spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
    spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
    spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
    spring.security.oauth2.client.provider.google.jwk-set-uri=https://www.googleapis.com/oauth2/v3/certs
    
    

    React Logout component

    const Logout = () => {
        const handleLogout = async () => {
            try {
                const response = await axios.post('/auth/logout');
                console.log(response.data);
                // Handle logout success (e.g., redirect or clear auth state)
            } catch (error) {
                console.error('Logout failed:', error);
            }
        };
    
        return (
            <button onClick={handleLogout}>Logout</button>
        );
    };
    
    Login or Signup to reply.
  2. It would be a bad experience for users to be disconnected from Google when they log out from your app. But if their Google session remains active, then their next "login with Google" from within your app will run silently and they’ll feel like they never logged out from your app.

    A solution is to use an authorization server of your own in front of Google. Almost all OIDC Providers implement "Login with …" (Keycloak, Auth0, or in this case, maybe Spring Authorization Server). Like that, you can end the session on the authorization without closing the social login provider session. Also, this will have several side benefits like enabling you to manage user data (add stuff like roles).

    I wrote a tutorial for getting started with Spring & Keycloak on Baeldung.

    I wrote another tutorial about the OAuth2 BFF pattern for single-page applications. It covers React web apps.

    In this other answer, I detailed what it takes to authorize requests with sessions (and CSRF token) from a mobile app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search