Before we start writing a Registration & Login example using JWT integration we need to understand below list of classes and its usage.
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
Full source code is available in GitHub Repository: Customer registration and Login using JWT token Example