我基于UsernamePasswordAuthenticationFilter需要的自定义过滤器,AuthenticationManager但每次我调用该方法时,attemptAuthentication()编译都会在这里失败:Authentication auth2 = this.getAuthenticationManager().authenticate(authRequest);为AuthenticationManager空:java.lang.NullPointerException: null at app.shellx.security.CustomUsernamePasswordAuthenticationFilter.attemptAuthentication(CustomUsernamePasswordAuthenticationFilter.java:75) ~[classes/:na]Web安全配置@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserService userService; @Autowired private JwtTokenFilter jwtTokenFilter; @Autowired private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http .httpBasic().disable() .addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class) .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .cors().and() .csrf().disable() .authorizeRequests() // .antMatchers("/**") .antMatchers("/login/**", "/register/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() //.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); .addFilterAt(new CustomUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .formLogin() .loginPage("http://localhost:4200/login")//.failureUrl("/login-error") .loginProcessingUrl("/login") .usernameParameter("email") .successHandler(customAuthenticationSuccessHandler) .and() .logout() .permitAll(); }
1 回答
森栏
TA贡献1810条经验 获得超5个赞
您CustomUsernamePasswordAuthenticationFilter
不是由 Spring 管理的(因为您直接创建了它),因此您的过滤器中没有 Spring 管理的依赖项注入行为。这就是为什么AuthenticationManager
从未注入并且现在为空的原因。
假设你把你的AuthenticationManager
作为一个豆子暴露出来......
您可以通过您的方法使您的过滤器成为一个 bean(注意在 Spring Boot 中自动注册
Filter
bean)@Bean
WebSecurityConfig
或者您可以在创建过滤器对象时简单地将 传递给
AuthenticationManager
您的过滤器(通过其构造函数或设置器)。没有必要将过滤器公开为 bean。
添加回答
举报
0/150
提交
取消