Spring Security整合Jwt认证时AuthenticationManager Bean缺失求助
Spring Security JWT认证:AuthenticationManager Bean找不到问题
问题详情
环境信息:
java version - 1.8 spring version - 2.3.3.RELEASE
报错信息:
Description: Field authenticationManager in com.exam.skillassess.controller.AuthenticationController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
注入点注解:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
官方建议:
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
已尝试相关方案但未解决,以下是相关代码:
认证控制器类
@RestController public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private JwtUtils jwtUtils; @PostMapping("/generate-token") public ResponseEntity<?> generateToken(@RequestBody JwtRequest request) throws Exception{ try { authenticate(request.getUsername(), request.getPassword()); }catch(UsernameNotFoundException e) { e.printStackTrace(); throw new Exception("User not found Exception"); } UserDetails userDetails = this.userDetailsService.loadUserByUsername(request.getUsername()); String token = this.jwtUtils.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } private void authenticate(String username, String password) throws Exception { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); }catch(DisabledException e) { throw new Exception("User Disabled" + e.getMessage()); }catch(BadCredentialsException e) { throw new Exception("Bad Credentials" + e.getMessage()); } } }
安全配置类
@EnableWebSecurity @Configuration public class MySecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired private JwtAuthenticationEntryPoint unAuthorizedHandler; @Autowired private JwtAuthenticationFilter jwtAuthenticationFilter; @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Autowired private UserDetailsServiceImpl userDetailsServiceImpl; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(this.userDetailsServiceImpl).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .cors() .disable() .authorizeRequests() .antMatchers("/generate-token", "/user/").permitAll() .antMatchers(HttpMethod.OPTIONS).permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(unAuthorizedHandler) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class); } }
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/><!--lookup parent from repository --> </parent> <groupId>com.exam</groupId> <artifactId>skillassess</artifactId> <version>0.0.1-SNAPSHOT</version> <name>skillassess</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <!-- Security dependencies for jwt --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <!-- Security dependencies for jwt --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
问题排查与解决
你的代码已重写authenticationManagerBean()并添加@Bean注解,但仍出现Bean找不到问题,可从以下方向排查:
1. 组件扫描范围问题
确保MySecurityConfig所在包被Spring Boot启动类扫描覆盖。检查启动类的@SpringBootApplication注解是否包含配置类所在包,或手动添加@ComponentScan指定路径:
@SpringBootApplication(scanBasePackages = "com.exam.skillassess") public class SkillassessApplication { public static void main(String[] args) { SpringApplication.run(SkillassessApplication.class, args); } }
2. 依赖缓存与版本兼容
执行Maven清理命令,重新下载依赖,排除缓存或版本冲突问题:
mvn clean install -U
3. 注入方式优化
改用构造方法注入(Spring官方推荐),避免字段注入可能的初始化顺序问题:
@RestController public class AuthenticationController { private final AuthenticationManager authenticationManager; private final UserDetailsServiceImpl userDetailsService; private final JwtUtils jwtUtils; public AuthenticationController(AuthenticationManager authenticationManager, UserDetailsServiceImpl userDetailsService, JwtUtils jwtUtils) { this.authenticationManager = authenticationManager; this.userDetailsService = userDetailsService; this.jwtUtils = jwtUtils; } // 原有业务方法保持不变 }
4. JwtAuthenticationFilter的Bean声明
确保JwtAuthenticationFilter类上添加@Component注解,让Spring能扫描并创建该Bean,避免配置类中@Autowired导致的初始化顺序异常:
@Component public class JwtAuthenticationFilter extends OncePerRequestFilter { // 你的过滤逻辑实现 }
内容的提问来源于stack exchange,提问作者Tarun Kumar
相关产品推荐
相关产品推荐

