下面是我在web.xml中的配置,我有一个JwtFilter,但在调用其他URL时无法访问。
的web.xml
<web-app
<display-name>Portal Web</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet-spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>jwtFilter</filter-name>
<filter-class>com.pingle.lola.authentication.JwtFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>jwtFilter</filter-name>
<url-pattern>/portal/lola/*</url-pattern>
</filter-mapping>
这是我的JwtFilter
public class JwtFilter extends GenericFilterBean {
@Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
System.out.println("came here");
final String authHeader = request.getHeader("Authorization");
System.out.println("came here - " + authHeader);
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
System.out.println("should throw");
throw new ServletException("Missing or invalid Authorization header.");
}
final String token = authHeader.substring(7); // The part after "Bearer "
System.out.println("came here" + token);
try {
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
}
catch (final SignatureException e) {
throw new ServletException("Invalid token.");
}
chain.doFilter(req, res);
}
}
我有控制器,其中基本的休息API被配置。我正在尝试检查是否有任何URL像localhost:8080 / portal / lola / getData那样。它应该转到JwtFilter并在请求的标头中检查身份验证令牌,如果有效则在控制器上传递其他明智的抛出错误消息。逻辑写得正确,但是没有调用过滤器,当我点击上面的URL时,它直接进入控制器而没有到达过滤器。
我的spring config.xml
<context:component-scan base-package="com.pingle.lola.controller"/>
<mvc:annotation-driven/>
//不知道为什么我没有映射到任何控制器时创建它:(
<mvc:default-servlet-handler/>
答案 0 :(得分:0)
似乎/portal
是应用程序上下文的名称。过滤器url-pattern不应包含上下文的名称。这意味着,过滤器网址格式应为/lola/*
,而不是/portal
。尝试将过滤器映射更改为:
<filter-mapping>
<filter-name>jwtFilter</filter-name>
<url-pattern>/lola/*</url-pattern>
</filter-mapping>