前言
项目启动报错,required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
项目启动创建`SysLoginController`时找不到`org.springframework.security.authentication.AuthenticationManager`问题原因,解决方案,原理及源码分析
- 前言
- 1 具体问题
- 2 问题原因
- 3 解决方案
- 4 原理分析
1 具体问题
项目启动报错,具体报错信息如下
2024-10-21 10:30:54.538 ERROR 17676 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : ***************************
APPLICATION FAILED TO START
***************************Description:Field loginService in com.haixin.initadmin.controller.system.SysLoginController 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.
2 问题原因
项目启动创建SysLoginController
时找不到org.springframework.security.authentication.AuthenticationManager
3 解决方案
- 没有引入
spring-boot-starter-security
pom依赖,如果是这个问题,一般在开发阶段就可以发现爆红出差。只需引入以下依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 自定义配置类中定义
AuthenticationManager
Bean
在spring boot 2.0X的默认配置中,不再自动注册AuthenticationManager
,如果使用自定义的安全配置类,需要手动暴露AuthenticationManager
Bean
如下:
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.configuration.AuthenticationConfiguration;@Configuration
public class SecurityConfig {@Beanpublic AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {return authenticationConfiguration.getAuthenticationManager();}
}
4 原理分析
AuthenticationManager
是 Spring Security 框架中的一个核心接口,用于处理用户的认证逻辑。在应用程序中,当用户登录时,AuthenticationManager
负责验证用户的凭据,并决定是否允许用户访问系统。