javaspring-bootjwtspring-boot-security

Spring Boot APPLICATION FAILED TO START due to required a bean of type AuthenticationManager


I am working in a spring web application with JWT.

Spring Boot: 3.1.0

Java: 17

Database: mysql

I can able to build successfully. When I try to run, then getting an error

Field authenticationManager in com.myapp.controller.LoginController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

enter image description here

***************************
APPLICATION FAILED TO START
***************************

Description:

Field authenticationManager in com.myapp.controller.LoginController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.

LoginController

@Slf4j
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    UserRepository userRepository;

    @Autowired
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public ResponseEntity<Object> login(@Validated(ValidationOrder.class) Login loginData,
            BindingResult bindingResult) {

        try {

            Optional<User> user = userRepository.findByUserEmailAddress(loginData.getUserEmailAddress());

            if (user.isPresent() && user.get().getUserPassword().equals(loginData.getUserPassword())) {

                return ResponseEntity.ok(
                        new RestResponse(ResponseStatus.SUCCESS.toString(), "Login Success", user.get().getUserName()));

            } else {

                return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(),
                        "Login Failed. Invalid username or password!!!", null));
            }

        } catch (Exception ex) {

            log.error(null, ex);
            return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(), ex.getMessage(), null));
        }
    }
}

ApplicationSecurity

@Configuration
@EnableMethodSecurity
public class ApplicationSecurity {//extends WebSecurityConfiguration {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    JwtUserDetailsService jwtUserDetailsService;

    @Bean
    public JwtAuthenticationFilter authenticationJwtTokenFilter() {

        return new JwtAuthenticationFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {

        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(jwtUserDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

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

        //@formatter:off
        http.csrf(csrf -> csrf.disable())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll()
                                                   //.requestMatchers("/api/test/**").permitAll()
                                                   .anyRequest()
                                                   .authenticated()
                                      );
        //@formatter:on

        http.authenticationProvider(authenticationProvider());

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

        return http.build();
    }
}

JwtAuthenticationEntryPoint

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -7858869558953243875L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

Any idea about this error.


Solution

  • just add a bean in your ApplicationSecurity what is Global AuthenticationManager

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

    Finally it will work.