Spring Security JWT Authntication Registration & Login

Before we start writing a Registration & Login example using JWT integration we need to understand below list of classes and its usage.

  1. SecurityConfiguration: This file contains all the spring security related configuration like accessing of the enpoits with and without authentication token, also we can set the session type, authentication filter type etc.
  2. JwtService: This will work like a service layer in JWT, here will implement some mandatory method like generateToken, extractUsername from token and validateToken
  3. JwtAuthFilter: This class will extends with OncePerRequestFilter abstract class to override the doFilterInternal method to perform the operations like Bearer token validation and from this method will invoke the loadUserByUsername method which is available in UserDetailsService interface.
  4. UserDetailsServiceImpl: This class implements UserDetailsService to provide the implementation for the loadUserByUsername method.

JWT authentication using spring security execution flow

Registration and Login example
Project structure

SecurityConfig

If you see in the below class we have added the following enpoints "/auth/welcome", "/auth/create/user", "/auth/login" we excluded from the security. It means without providing any token or authentication details will be able to access these endpoints.


                        @Configuration
                        @EnableWebSecurity
                        @EnableMethodSecurity
                        public class SecurityConfig {

                            @Autowired
                            private JwtAuthFilter authFilter;

                            // User Creation
                            @Bean
                            public UserDetailsService userDetailsService() {
                                return new UserDetailsServiceImpl();
                            }

                            // Configuring HttpSecurity
                            @Bean
                            public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
                                return http.csrf(csrf -> csrf.disable())
                                        .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/welcome", "/auth/create/user", "/auth/login").permitAll())
                                        .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/user/**").authenticated())
                                        .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/**").authenticated())
                                        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                                        .authenticationProvider(authenticationProvider())
                                        .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                                        .build();
                            }

                            @Bean
                            public PasswordEncoder passwordEncoder() {
                                return new BCryptPasswordEncoder();
                            }

                            @Bean
                            public AuthenticationProvider authenticationProvider() {
                                DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
                                authenticationProvider.setUserDetailsService(userDetailsService());
                                authenticationProvider.setPasswordEncoder(passwordEncoder());
                                return authenticationProvider;
                            }

                            @Bean
                            public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
                                return config.getAuthenticationManager();
                            }
                            
                        }               
                    

Download the full code from the Github repository, link is given below, and check the Customer registration and login example code how it as been implemented.

Check below postman call we will be able to access above excluded enpoints without any authentication

/auth/welcome

/auth/create/user

/auth/login

Full source code is available in GitHub Repository: Customer registration and Login using JWT token Example