java - 无法在 Spring 中自动连接我的身份验证过滤器中的服务

标签 java spring hibernate spring-mvc

我正在尝试通过 token 对用户进行身份验证,但是当我尝试在 AuthenticationTokenProcessingFilter 内自动连接我的服务时,我得到空指针异常。 因为 autowired 服务为空,我该如何解决这个问题?

我的 AuthenticationTokenProcessingFilter

@ComponentScan(basePackages = {"com.marketplace"})
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired
    @Qualifier("myServices")
    private MyServices service;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if (parms.containsKey("token")) {
            try {
                String strToken = parms.get("token")[0]; // grab the first "token" parameter

                User user = service.getUserByToken(strToken);
                System.out.println("Token: " + strToken);

                DateTime dt = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                DateTime createdDate = fmt.parseDateTime(strToken);
                Minutes mins = Minutes.minutesBetween(createdDate, dt);


                if (user != null && mins.getMinutes() <= 30) {
                    System.out.println("valid token found");

                    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

                    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword());
                    token.setDetails(new WebAuthenticationDetails((HttpServletRequest) request));
                    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword(), authorities); //this.authenticationProvider.authenticate(token);

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }else{
                    System.out.println("invalid token");
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("no token found");
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

我尝试在 AppConfig

中添加以下内容
@Bean(name="myServices")
    public MyServices stockService() {
        return new MyServiceImpl();
    }

我的 AppConfig 注释是

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.marketplace")
public class AppConfig extends WebMvcConfigurerAdapter {

最佳答案

您不能从开箱即用的过滤器中使用依赖注入(inject)。尽管您使用的是 GenericFilterBean,但您的 Servlet 过滤器不是由 spring 管理的。正如 javadocs 所指出的

This generic filter base class has no dependency on the Spring org.springframework.context.ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see org.springframework.web.context.support.WebApplicationContextUtils).

简单地说,我们不能期望 spring 注入(inject)服务,但我们可以在第一次调用时懒惰地设置它。 例如

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
    private MyServices service;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(service==null){
            ServletContext servletContext = request.getServletContext();
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            service = webApplicationContext.getBean(MyServices.class);
        }
        your code ...    
    }

}

关于java - 无法在 Spring 中自动连接我的身份验证过滤器中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494398/

相关文章:

java - 如何设置 JFrame 背景透明但 JPanel 或 JLabel 背景不透明?

java - Android Retrofit请求如何在主线程中获取Retrofit响应

java - 创建名称为 'securityConfig' 的 bean 时出错 : Injection of autowired dependencies failed

java - 选择图库中的图像

java - 异常、算术异常和对象

spring - Grails 中的加载时间编织

spring - ant.propertyFile每次都会更新评论

hibernate - Hibernate Session.load()何时抛出异常

java - org.hibernate.LazyInitializationException : failed to lazily initialize a collection of role during login in spring security

java - 多个应用程序的相同 Hibernate Search Lucene 索引