首页 > 解决方案 > Spring Security (java.lang.NullPointerException: null at org.springframework.security.authentication.ProviderManager.authenticate)

问题描述

我有弹簧安全问题。我是新手,所以不明白为什么它有时会起作用。(主类的每 2 次或第 3 次重启我都会从 ProviderManager 获得空指针)。因为我认为我的 UserDetailsS​​ervice 实现的 loadUserByUsername 方法当时不会在 spring 调用。

错误堆栈跟踪

2018-06-27 05:07:39.180  INFO 5556 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms
2018-06-27 05:07:40.984  WARN 5556 --- [nio-8080-exec-2] o.a.c.util.SessionIdGeneratorBase        : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [101] milliseconds.
2018-06-27 05:07:42.285 ERROR 5556 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.NullPointerException: null
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:164) ~[spring-security-core-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]

我的配置

@Configuration
@ComponentScan("hello")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    Logger log = LoggerFactory.getLogger(WebSecurityConfig1.class);

    @Autowired
    public PasswordEncoder passwordEncoder;

    private AuthenticationProvider authenticationProvider;

    @Autowired
    @Qualifier("daoAuthenticationProvider")
    public void setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;

    }


    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(PasswordEncoder passwordEncoder,
                                                               UserDetailsService userDetailsService){ 
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return daoAuthenticationProvider;
    }

    @Autowired
    public void configureAuthManager(AuthenticationManagerBuilder authenticationManagerBuilder){
        authenticationManagerBuilder.authenticationProvider(authenticationProvider);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
}

用户详情服务

@Service("userDetailsService")
public class UDservice implements UserDetailsService {

    Logger log = LoggerFactory.getLogger(UDservice1.class);

    @Autowired
    UserRepository repository;

    public UserDetails converter(User user) {
        UserDetailsImpl userDetails = new UserDetailsImpl();
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPwd());
        userDetails.setEnabled(user.getEnabled());
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole()));
        userDetails.setAuthorities(authorities);
        return userDetails;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username != null){
         return  converter(repository.findByUsername(username));
        }
        else
            throw new UsernameNotFoundException("null at name");
    }
}

标签: springsecurityjpa

解决方案


我也有这个例外。如果您没有通过任何身份验证提供程序,您将收到此异常。

如果您没有提供身份验证提供程序 或者 您通过 null

  1. 在我的情况和 OP 的情况下Missed@Autowired
    (我配置了授权和身份验证,但 null 已通过)
//Missed autowired annotation
private CustomAuthenticationProvider customAuthenticationProvider;

并尝试注入 null

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception 
  {
      auth.authenticationProvider(customAuthenticationProvider); // Null passed here
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
          .antMatchers("/**").hasRole("ADMIN")
          .anyRequest()
          .authenticated()
          .and()
          .formLogin();
  }
  1. 您可能错过了注入 authenticationProvider 依赖
    .authenticationProvider(customAuthenticationProvider)
    项或
    注释行
    //.authenticationProvider(customAuthenticationProvider)

推荐阅读