我基于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
提交
取消