【问题标题】:Spring not autowiring AuthenticationManagerSpring不自动装配AuthenticationManager
【发布时间】:2016-11-19 13:12:09
【问题描述】:

我在 IntelliJ 中使用 Spring boot 来创建 Spring MVC 项目。 我正在使用 Spring 安全性来验证用户身份。我按照指南找到了here

这是我的 SecurityService 类:

@Service
public class SecurityService {

    @Autowired
    private AuthenticationManager authenticationManager;

    private UserDetailsService userDetailsService = new UserDetailsServiceImpl();

    public String findLoggedInUsername() {
        Object userDetails = SecurityContextHolder.getContext();
        if (userDetails instanceof UserDetails) {
            return ((UserDetails)userDetails).getUsername();
        }
        return null;
    }

    public void autologin(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails.getUsername().equals("NotFound")) {
            return;
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

        authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        if (usernamePasswordAuthenticationToken.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
}

然后我在 securityConfig.xml 中定义了这些行:

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsServiceImpl">
        <password-encoder ref="encoder"></password-encoder>
    </authentication-provider>
</authentication-manager>

在 IntelliJ 中,authenticationManager 旁边有一个 bean 图标,当我单击它时,它会将我定向到 AuthenticationManager 的 Bean 定义。

但是,当我尝试编译时,Spring 给了我这个错误:

project.service.SecurityService 中的字段 authenticationManager 需要一个 bean 类型 'org.springframework.security.authentication.AuthenticationManager' 找不到。

  • Bean 方法 'authenticationManager' 未加载,因为 @ConditionalOnBean(类型: org.springframework.security.config.annotation.ObjectPostProcessor; SearchStrategy: all) 没有找到任何 bean

为什么 Spring 找不到 bean,而 IntelliJ 可以?我该如何解决这个问题?

顺便说一句,我的大部分配置都是使用 Spring Boot Autoconfiguration 完成的。我已经尝试添加@Qualifier("authenticationManager"),但没有奏效。

【问题讨论】:

    标签: java spring intellij-idea spring-security spring-boot


    【解决方案1】:

    我认为component-scan 存在问题。您可以在securityConfig.xml 中创建bean SecurityService,如下所示。

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userDetailsServiceImpl">
            <password-encoder ref="encoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>
    
    <bean id="securityService" class="SecurityService" />
    

    【讨论】:

    • 嗨,对不起,我应该包含整个 xml 文件。我的配置文件中已经有这一行:
    猜你喜欢
    • 2017-04-29
    • 2019-05-19
    • 2015-09-17
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多