How Spring Security Authentication Flow Has Been Implemented in AdventureTube auth-service Module

 

1. 🎯 Purpose

This document explains how Spring Security’s authentication flow is custom-configured and used inside the auth-service module of the AdventureTube microservices system, especially for authenticating users via Google ID tokens.


2. 🔐 Authentication Scenario

  • The only point where authentication is explicitly triggered is during POST /auth/issueToken.

  • This endpoint receives a valid Google ID token, extracts the user’s email and Google subject ID, and uses Spring Security to authenticate.


3. ⚖️ Custom Authentication Provider Registration

  • A CustomAuthenticationProvider is defined, extending DaoAuthenticationProvider.

  • It sets a custom UserDetailsService (i.e., CustomUserDetailsService) and a PasswordEncoder.

  • This provider allows overriding the authenticate() method to customize the authentication logic.

Registration Flow:

  1. In AuthServiceConfig, Spring creates an AuthenticationManager bean.

  2. The customAuthenticationProvider() method returns a new CustomAuthenticationProvider instance.

  3. This provider is registered with Spring Security:

    AuthenticationManagerBuilder authenticationManagerBuilder = 
        httpSecurity.getSharedObject(AuthenticationManagerBuilder.class);
    authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider());
    return authenticationManagerBuilder.build();
    

4. ⚡️ Triggering the Custom Authentication Logic

  • In AuthService.issueToken(), the following line initiates the authentication process:

    Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(email, googleId));
    

What happens under the hood:

  1. Spring Security passes the token to the registered CustomAuthenticationProvider.

  2. Inside CustomAuthenticationProvider.authenticate(), it does:

    UserDetails userDetails = getUserDetailsService().loadUserByUsername(email);
    
  3. This calls CustomUserDetailsService.loadUserByUsername(email).

  4. CustomUserDetailsService uses RestTemplate to call the member-service to retrieve user data.

  5. Spring compares the raw googleId with the stored encoded password using the PasswordEncoder.

  6. On success, the Authentication object is returned and used to issue JWT tokens.


Leave a Comment

Your email address will not be published. Required fields are marked *