Spring REST API - 来自Filter的服务调用提供空指针异常

时间:2018-01-23 04:19:42

标签: spring rest authentication filter

我有基于Spring的REST API,我正在尝试添加自定义过滤器。此过滤器将用于基于令牌的验证。但是,服务调用会给出空指针异常。过滤器也会添加到web.xml下以进行注册。

以下服务调用给出空指针。请注意,我没有使用Spring安全性进行身份验证。

boolean flag = authTokenService.validateRESTAccessRequest(authToken);

其余的代码工作正常。我尝试使用扩展的OncePerRequestfilter而不是GenericFilter bean来编辑过滤器。但同样的问题仍然存在。需要做什么?

package org.application.web.filter;

  import java.io.IOException;
  import javax.servlet.FilterChain;
  import javax.servlet.ServletException;
  import javax.servlet.ServletOutputStream;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.application.services.AuthTokenService;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Component;
  import org.springframework.web.filter.GenericFilterBean;

  @Component
  public class RestApiAuthFilter extends GenericFilterBean {
    @Autowired
    AuthTokenService authTokenService;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {

         final HttpServletRequest request = (HttpServletRequest) req;
         final HttpServletResponse response = (HttpServletResponse) res;
         final String authHeader = request.getHeader("Authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);

            filterChain.doFilter(request, response);
        } else {

            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                ServletOutputStream os = response.getOutputStream();
                os.write("INVALID AUTHNETICATION TOKEN".getBytes());
                os.close();

                return;
            }

            final String authToken = authHeader.substring(7);
            boolean flag = authTokenService.validateRESTAccessRequest(authToken);

            if (flag == false) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                ServletOutputStream os = response.getOutputStream();
                os.write("INVALID AUTHNETICATION TOKEN".getBytes());
                os.close();

                return;
            } else {
                filterChain.doFilter(request, response);
            }
        }

    }
    }

web.xml下面有过滤条目,

<filter>
        <filter-name>restApiAuthFilter</filter-name>
        <filter-class>org.application.web.filter.RestApiAuthFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>restApiAuthFilter</filter-name>
        <url-pattern>/secure/*</url-pattern>
    </filter-mapping>

错误的堆栈跟踪如下,

java.lang.NullPointerException
    at org.application.web.filter.RestApiAuthFilter.doFilter(RestApiAuthFilter.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.application.web.filter.CORSFilter.doFilterInternal(CORSFilter.java:27)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:0)

我可以解决这个问题。以下链接来救援......

Access to spring beans from OncePerRequestFilter

我做了以下更改

<强>的web.xml

<filter>
    <filter-name>RestApiAuthFilter</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>RestApiAuthFilter</filter-name>
    <url-pattern>/secure/*</url-pattern>
</filter-mapping>

spring context xml

<bean name="RestApiAuthFilter" class="org.application.web.filter.RestApiAuthFilter">
       <property name="authTokenService" ref="authTokenService"/>
    </bean>

    <bean id="authTokenService"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager" ref="transactionManager" />
        <property name="target" ref="authTokenServiceTarget" />
        <property name="proxyInterfaces">
            <value>org.application.services.AuthTokenService</value>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="*">PROPAGATION_NOT_SUPPORTED, readOnly</prop>
            </props>
        </property>
    </bean>
    <bean id="authTokenServiceTarget"
        class="org.application.services.impl.AuthTokenServiceImpl">
    </bean>

<强> RestApiAuthFilter.java

package org.application.web.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.application.services.AuthTokenService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class RestApiAuthFilter extends OncePerRequestFilter {

    AuthTokenService authTokenService;

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

        final String authHeader = request.getHeader("Authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);

            filterChain.doFilter(request, response);
        } else {

            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                ServletOutputStream os = response.getOutputStream();
                os.write("INVALID AUTHNETICATION TOKEN".getBytes());
                os.close();

                return;
            }

            boolean flag = authTokenService.validateRESTAccessRequest(request);

            if (flag == false) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                ServletOutputStream os = response.getOutputStream();
                os.write("INVALID AUTHNETICATION TOKEN".getBytes());
                os.close();

                return;
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }

    public AuthTokenService getAuthTokenService() {
        return authTokenService;
    }

    public void setAuthTokenService(AuthTokenService authTokenService) {
        this.authTokenService = authTokenService;
    }
}