this.authenticationManager" 为空

Posted

技术标签:

【中文标题】this.authenticationManager" 为空【英文标题】:this.authenticationManager" is null 【发布时间】:2022-01-12 22:49:00 【问题描述】:
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api/auth/")
public class LoginController 
    private AuthenticationManager authenticationManager;

    JwtTokenProvider jwtTokenProvider;

    public JwtTokenProvider jwtTokenProvider() 
        return jwtTokenProvider;
    

    @Autowired
    UserRepository users;

    @Autowired
    private CustomUserDetailsService userService;

    @SuppressWarnings("rawtypes")
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody AuthBody data) 
        try 
            String username = data.getEmail();
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
            String token = jwtTokenProvider.createToken(username, this.users.findByEmail(username).getRoles());
            Map<Object, Object> model = new HashMap<>();
            model.put("username", username);
            model.put("token", token);
            // return ResponseEntity.ok(model);
            return new ResponseEntity<>(model.toString(), HttpStatus.OK);

         catch (AuthenticationException e) 
            throw new BadCredentialsException("Invalid email/password supplied");
        
    
    

我的网络安全配置:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
    @Bean( name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean() ;
    
    @Autowired
    JwtTokenProvider jwtTokenProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        UserDetailsService userDetailsService = mongoUserDetails();
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());

    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.httpBasic().disable().csrf().disable().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers("/api/auth/login").permitAll().antMatchers("/api/auth/register").permitAll()
                .antMatchers("/api/products/**").hasAuthority("ADMIN").anyRequest().authenticated().and().csrf()
                .disable().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint()).and()
                .apply(new JwtConfigurer(jwtTokenProvider));
        http.cors();
    

    @Override
    public void configure(WebSecurity web) throws Exception 
        web.ignoring().antMatchers("/**");
    

    @Bean
    public PasswordEncoder bCryptPasswordEncoder() 
        return new BCryptPasswordEncoder();
    



    @Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() 
        return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Unauthorized");
    

    @Bean
    public UserDetailsService mongoUserDetails() 
        return new CustomUserDetailsService();
    

我总是在 authentiticationMnager.authenticate 上遇到空指针异常!

我正在使用 spring security v 1.1.1 版本和 jjwt 版本 0.9.1。

authenticationManager 始终为 null。

【问题讨论】:

请阅读:Why is “Can someone help me?” not an actual question? --- 请edit 问题并删除无意义的文本。 --- 你为什么认为AuthenticationManager 不是null 该字段上没有 @Autowired 那么 Spring 怎么知道它应该自动装配该字段? 【参考方案1】:

这已经解决了。

我的错误是错误的包路径。

【讨论】:

【参考方案2】:

你能在 WebSecurityConfig 类中试试这个注解吗

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

【讨论】:

我非常怀疑这能否解决手头的问题。如果没有注解或构造函数,启用全局方法安全性不会自动激活注入。 并添加 enableWebSecurity 注释。我认为它正在工作。楼主会说结果的。如果您有更好的答案,请告诉我们 即使我在 websecurityConfig 中添加了这些注释,我仍然遇到同样的问题 java.lang.NullPointerException:无法调用“org.springframework.security.authentication.AuthenticationManager.authenticate(org.springframework.security.core.Authentication)”,因为“this.authenticationManager”为空跨度> 你好,如果我在 authenticationManager 上添加这个自动装配,我会收到这个错误:com.geoteck.controller.LoginController 中的字段 authenticationManager 需要一个 'org.springframework.security.authentication.AuthenticationManager' 类型的 bean找不到。

以上是关于this.authenticationManager" 为空的主要内容,如果未能解决你的问题,请参考以下文章