【问题标题】:Autowiring Spring AuthenticationManager Filter always gives null自动装配 Spring AuthenticationManager 过滤器总是给出 null
【发布时间】:2017-04-29 02:07:06
【问题描述】:

我需要在自定义过滤器中使用 Spring Security 的 AuthenticationManagerBean,但它似乎总是给出一个空值。我正在使用弹簧靴 1.3.8。这是代码中的一个sn-p:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {


        @Override
        @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {

     }



}

过滤代码:

public class MyFilter extends OncePerRequestFilter {

  private TokenExtractor tokenExtractor = new BearerTokenExtractor();

  @Autowired
    private AuthenticationManager authenticationManager;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {


            //some checks

Authentication receivedAuthentication = tokenExtractor.extract(request);
receivedAuthentication.setAuthenticated(true);
                authenticationManager.authenticate(receivedAuthentication);
                 SecurityContextHolder.getContext().setAuthentication(receivedAuthentication);

        }
    }



}

由于 authenticationManager 为空而引发异常。

感谢您的帮助。

【问题讨论】:

标签: java spring spring-boot spring-security


【解决方案1】:

BeanIds.AUTHENTICATION_MANAGER的值为"org.springframework.security.authenticationManager";因此,您没有名为 "authenticationManager" 的 bean。

另外,我认为你的过滤器上需要@Component。

祝你好运。

【讨论】:

  • 感谢您的建议。它仍然给出 null 。我也尝试过使用@Qualifier@Autowired,但同样的事情。
  • 我认为你的过滤器需要@Component。我收回了重命名该方法的建议;我错过了它正在覆盖现有方法。
  • 变化不大,还是谢谢,我找到了另一种设置身份验证的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2017-11-27
  • 2016-03-17
  • 2014-09-08
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多