96

I am trying to update the WebSecurityConfigurerAdapter as it has been deprecated. The class is configured as follows:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UsuariService userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;
    
    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers("/api/auth/**").permitAll().antMatchers("/api/test/**").permitAll().antMatchers("/api/v1/**").permitAll().anyRequest()
                .authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}

Now without the WebSecurityConfigurerAdapter I redefine the same class like this:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    @Autowired
    UsuariService userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Bean
    AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
        return builder.userDetailsService(userDetailsService).passwordEncoder(encoder()).and().build();
    }

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .antMatchers("/api/test/**").permitAll()
                .antMatchers("/api/v1/**").permitAll()
                .anyRequest().authenticated();
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}

But unfortunately I get the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': 
  Unsatisfied dependency expressed through method 'setFilterChains' parameter 0; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'filterChain' defined in class path resource [cit/base/app/security/WebSecurityConfig.class]: 
  Unsatisfied dependency expressed through method 'filterChain' parameter 0; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.httpSecurity' defined in class path resource [org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]: 
Bean instantiation via factory method failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
  Failed to instantiate [org.springframework.security.config.annotation.web.builders.HttpSecurity]: Factory method 'httpSecurity' threw exception; 
nested exception is java.lang.IllegalStateException: 
  Cannot apply org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$EnableGlobalAuthenticationAutowiredConfigurer@3fdc705c to already built object

I would appreciate any kind of help that would be most welcome.

aSemy
  • 5,485
  • 2
  • 25
  • 51
Ramon J.
  • 1,137
  • 1
  • 9
  • 7
  • 1
    Welcome to Stack Overflow. It might help if you replace the two `@Autowired` fields with parameter injection into the `@Bean` methods instead. – Andy Wilkinson May 25 '22 at 17:44
  • 3
    I am doing the exact thing, trying to update the WebSecurityConfig. I have found this tutorial: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter. I don't really know how to update my methods according to it but maybe you do. Hope it helps! – Gloria May 26 '22 at 11:47
  • For anyone looking for an example, I found this https://www.codejava.net/frameworks/spring-boot/fix-websecurityconfigureradapter-deprecated. Hope it helps!! – Praveen G Jun 14 '22 at 00:57
  • More here for anyone using JWT filter : https://stackoverflow.com/questions/71281032/spring-security-exposing-authenticationmanager-without-websecurityconfigureradap – Yann39 Jul 10 '22 at 21:43

8 Answers8

71

I have managed to update the methods. This is the WebSecurityConfig class, and the methods are modified in the following way:

public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

has become

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

In the old version you inject AuthenticationManagerBuilder, set userDetailsService, passwordEncoder and build it. But authenticationManager is already created in this step. It is created the way we wanted (with userDetailsService and the passwordEncoder).

Next, the configure() method for HttpSecurity is replaced by filterChain method as it is explained on the official site:

import com.myproject.UrlMapping;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
   private final UserDetailsService userDetailsService;

   private final AuthEntryPointJwt unauthorizedHandler;

   private final AuthTokenFilter authenticationJwtTokenFilter;

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

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

   @Bean
   public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
       http.cors().and().csrf().disable()
               .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
               .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
               .authorizeRequests()
               .antMatchers(UrlMapping.AUTH + UrlMapping.SIGN_UP).permitAll()
               .antMatchers(UrlMapping.AUTH + UrlMapping.LOGIN).permitAll()
               .antMatchers(UrlMapping.VALIDATE_JWT).permitAll()
               .antMatchers("/api/test/**").permitAll()
               .anyRequest().authenticated();

       http.addFilterBefore(authenticationJwtTokenFilter, UsernamePasswordAuthenticationFilter.class);

       return http.build();
   }

   @Bean
   public WebMvcConfigurer corsConfigurer() {
       return new WebMvcConfigurer() {
           @Override
           public void addCorsMappings(CorsRegistry registry) {
               registry.addMapping("/**")
                       .allowedMethods("*");
           }
       };
   }
}

I have added this in my build.gradle file:

implementation 'javax.xml.bind:jaxb-api:2.3.0'
Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
Gloria
  • 949
  • 3
  • 12
  • 2
    I have tested it and it works perfectly! I replaced the function configure() by authenticationManager() and it worked the first time. Thank you very much for the help! – Ramon J. May 27 '22 at 11:21
  • I'm so happy to hear that! You're welcome :) – Gloria May 27 '22 at 11:31
  • 3
    The idea is to get the default AuthenticationManager from AuthenticationConfiguration. This worked perfectly for me. Thank you !! – Amine Aouffen May 28 '22 at 16:43
  • You're welcome @AmineAouffen. So happy that it worked for you too – Gloria May 31 '22 at 11:39
  • 1
    Thanks, @Gloria, it worked for me also in the first attempt itself. Have searched on many websites but didn't find any where WebSecurtiyConfigurerAdapter is not used. So, I was stuck with my code But, you saved the day. :) – Yash Modi Jun 17 '22 at 17:44
  • 1
    Ohh I'm so glad to hear that. You're welcome @YashModi :) – Gloria Jun 17 '22 at 18:48
  • Hmm, struggeling with my old approach using JWTAuthenticationFilter. Wehre does the AuthTokenManager come from? – piet Jul 06 '22 at 10:39
  • 1
    this answer contains some faulty information. If you declare a `@Bean` there is no need to set the classes manually in the builder. Thats the whole point of a dependency injection framwork, spring will automatically inject the beans into the classes that need them. So the first declared code part of this answer is completely unneeded and never needed to be included in the first place. And the second part is also unneeded. The framework will automatically create an AuthenticationManager for you Downvoted – Toerktumlare Jul 14 '22 at 17:59
  • 1
    @Toerktumlare would you care to post an answer using something that is not in your opinion "faulty"? – cowley05 Aug 12 '22 at 15:31
  • Sure i can or i could give you a chance to correct your answer. But if you wish for me to write an answer i could do that. – Toerktumlare Aug 12 '22 at 17:30
  • The solution in this answer seems to cause a bean cycle to form. See [#11792](https://github.com/spring-projects/spring-security/issues/11792). The blog post detailing [deprecation of WebSecurityConfigurerAdapter](https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter) has an example of the suggested approach. – Steve Riesenberg Sep 09 '22 at 18:11
  • So the usersDetailService is obsolete to? – Yannick Mussche Dec 29 '22 at 10:51
16

I hope this configuration will work for UserDetailsService, AuthenticationManagerBuilder and AuthenticationManager.

@Configuration
public class BeanConfiguration {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@Configuration
public class SpringSecurityConfiguration {

    AuthenticationManager authenticationManager;

    @Autowired
    UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userDetailsService);
        authenticationManager = authenticationManagerBuilder.build();

        http.csrf().disable().cors().disable().authorizeHttpRequests().antMatchers("/api/v1/account/register", "/api/v1/account/auth").permitAll()
            .anyRequest().authenticated()
            .and()
            .authenticationManager(authenticationManager)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        return http.build();
    }

}
@Component
class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccountService accountService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        Account account = accountService.findAccountByEmail(email);
        return new UserPrincipalImp(account);
    }

    // ...
}
aSemy
  • 5,485
  • 2
  • 25
  • 51
Spring
  • 831
  • 1
  • 12
  • 42
7

change your file like this :

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SpringSecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.csrf().disable().cors().disable().authorizeHttpRequests()
                .requestMatchers("/user/register").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer();

        return http.build();
    }
}
invzbl3
  • 5,872
  • 9
  • 36
  • 76
jdev
  • 5,304
  • 1
  • 17
  • 20
5

The complete implementation of SecurityConfig class without extending the WebSecurityConfigurerAdapter is as follows.

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig {
    
        @Autowired
        private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    
        @Autowired
        UserDetailsService userDetailsService;
    
        @Autowired
        private JwtRequestFilter jwtRequestFilter;
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
            // We don't need CSRF for this example
            httpSecurity.csrf().disable()
                    // don't authenticate this particular request
                    .authorizeHttpRequests().antMatchers("/authenticate").permitAll()
                    // all other requests need to be authenticated
                    .anyRequest().authenticated().and()
                    // make sure we use stateless session; session won't be used to
                    // store user's state.
                    .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    
            // Add a filter to validate the tokens with every request
            httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
            return httpSecurity.build();
        }
    
        @Bean
        public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
            return authenticationConfiguration.getAuthenticationManager();
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
Sanchit Bhatnagar
  • 874
  • 2
  • 10
  • 16
Yash Modi
  • 127
  • 5
  • 2
    Hi! May I ask you how did you implement: "JwtAuthenticationEntryPoint" because I want to handle errors when I get wrong/expired... jwt – Robs Jul 12 '22 at 08:53
  • You can take a look at my repository for the implementation of Jwt. [Spring Boot app with Jwt](https://github.com/yashnmodi/rajblowplast-digital) – Yash Modi Jul 14 '22 at 01:07
  • this implementation is faulty, as spring security already has a customizable jwtfilter so implementing one is bad practice – Toerktumlare Jul 14 '22 at 18:03
  • @Toerktumlare don't you have an example code? – Robs Jul 30 '22 at 08:19
  • why didn't you just read the spring security documentation? Its on theirr website, and all you needed to do was to search the docs for "JWT" https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html – Toerktumlare Jul 30 '22 at 10:21
  • 1
    @Toerktumlare you're right, but sometimes there are cases of using JWT without OAuth2. – Sung.P Aug 12 '22 at 06:23
  • @Toerktumlare could you please provide some example of out-of-the-box solution with new Spring Security? I was not able to find anything. EVERY example in the Inernet describes custom implementations. Also, I didn't find anything in Spring Docs (regarding Username and Password authentication) – Kamil Oct 11 '22 at 16:03
  • Use FormLogin and then implement a `authenticationSuccessHandler` Where you create your JWT using nimbus. And then if you want to implement the handling of JWTs you can follow this https://thomasandolf.medium.com/spring-security-jwts-getting-started-ebdb4e4f1dd1 spring security has lots of ”username/password” authentican models described in the chapter ”Authentication” and a full solution for handling JWT – Toerktumlare Oct 11 '22 at 17:11
  • Why are you autowiring userDetailService? you are not using it – Yannick Mussche Dec 29 '22 at 10:52
1

It works in my case, the simplest way is to pass your userDetailService class directly in the SecurityFilterChain function.

Note : http.userDetailsService(customUserDetailService);

BCryptPasswordEncoder class automicaly get autowired as password Encoder, if @Bean method is avilable in configration.

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

Code :

package com.example.blogapi.config;

import com.example.blogapi.security.CustomUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {


    @Autowired
    private CustomUserDetailService customUserDetailService;


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {


        http
                .csrf().disable()
                .authorizeHttpRequests(
                        (authz) -> authz.anyRequest()
                                .authenticated())
                .httpBasic(Customizer.withDefaults())
                .userDetailsService(customUserDetailService);

        return http.build();
    }


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





}
Deepak Das
  • 177
  • 1
  • 6
  • 1
    no the simplest way is to just provide a bean of a UserDetailsService to the framework just like you are doing with bcrypt and the framework will handle the rest for you. – Toerktumlare Aug 25 '22 at 12:17
1

The below code demonstrates the possible solution of implementing Spring Security With Basic Authentication without WebSecurityConfigurerAdapter. Here, in the old version we inject AuthenticationManagerBuilder, set userDetailsService, passwordEncoder and build it. But AuthenticationManager is created the way we wanted (with userDetailsService and the passwordEncoder).

@Configuration
@EnableWebSecurity
public class SecurityConfig {

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

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // disabling csrf since we won't use form login
                .csrf().disable()
                // setting stateless session, because we choose to implement Rest API
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // giving permission to every request for /login endpoint
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                // for everything else, the user has to be authenticated
                .anyRequest().authenticated()
                .and()
                .httpBasic();

        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web -> web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**"));
    }
}
0
  • security config
@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        int rounds = 12;
        return new BCryptPasswordEncoder(rounds);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                .csrf()
                .disable()
                .httpBasic()
                .and()
                .authorizeHttpRequests()
                /*.requestMatchers("/user/**").hasRole("USER")*/
                .requestMatchers("/user/**", "/user/info/**").hasAuthority("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);;

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService customUserDetailsService) {

        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(customUserDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        List<AuthenticationProvider> providers =  List.of(authProvider);

        return new ProviderManager(providers);
    }
}

  • service
@Service
@RequiredArgsConstructor
public class CustomUserDetailService implements UserDetailsService {

    private final CustomerRepository customerRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        final CustomerModel customer = customerRepository.findByEmail(username); /*email*/

        Set<UserRole> roles = new HashSet<>();
        roles.add(new UserRole("USER"));
        roles.add(new UserRole("ADMIN"));

        if (customer == null) {
            throw new UsernameNotFoundException(username);
        }

        String email = customer.email();
        String password = customer.password();

        return User
                .withUsername(email)
                .password(password)
                /*.roles("USER")*/ /*Into a Security filter must be expression -> hasRole()*/
        
                .authorities(convertAuthorities(roles))
                .build();
    }

    private Set<GrantedAuthority> convertAuthorities(Set<UserRole> userRoles) {
        Set<GrantedAuthority> authorities=new HashSet<>();
        for (UserRole userRole : userRoles) {
            authorities.add(new SimpleGrantedAuthority(userRole.nameRole()));
        }
        return authorities;
    }
}

skyho
  • 1,438
  • 2
  • 20
  • 47
0

In Spring Security 6 there are a couple more changes

  • @EnableGlobalMethodSecurity is now deprecated, use @EnableMethodSecurity
  • antMatchers cannot be used, use requestMatchers
  • Method configureGlobal(AuthenticationManagerBuilder auth) doesn't work, refer to Gloria's answer to set JDBC Authentication

Code with Spring Boot 2.x

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Autowired
    public AuthTokenFilter authenticationJwtTokenFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests().antMatchers("/auth/**").permitAll().antMatchers("/test/**").permitAll()
        .antMatchers("/readiness_check").permitAll().antMatchers("/liveness_check").permitAll()
        .antMatchers("/_ah/start").permitAll().anyRequest().authenticated();
        

        http.addFilterBefore(authenticationJwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}

Code with Spring Boot 3.1.13

    @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Autowired
    public AuthTokenFilter authenticationJwtTokenFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests().antMatchers("/auth/**").permitAll().antMatchers("/test/**").permitAll()
        .antMatchers("/readiness_check").permitAll().antMatchers("/liveness_check").permitAll()
        .antMatchers("/_ah/start").permitAll().anyRequest().authenticated();
        

        http.addFilterBefore(authenticationJwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}

JWT creation also needs to be changed as jjwt dependency doesn't work. This page can be referred

Spring Security Reference doc