【问题标题】:spring boot filter don't return right response [duplicate]弹簧引导过滤器不返回正确的响应[重复]
【发布时间】:2016-04-12 14:51:47
【问题描述】:

我正在开发一个 spring boot 应用程序,我正在关注这个reply, 尽管需要进行一些调整才能使其在 Spring Boot 上工作,但一切正常,但问题是当我打电话时:

requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());

它返回“404 Not Found”而不是“401 Unauthorized”,该方法被调用,它捕获异常但返回错误状态。

Obs:如果我删除过滤器的约束,它会正常工作。

过滤器:

@Secured
@Provider
@Component
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        throw new NotAuthorizedException("Authorization header must be provided");
    }

    String token = authorizationHeader.substring("Bearer".length()).trim();

    try {

        validateToken(token);

    } catch (Exception e) {
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}

private void validateToken(String token) throws Exception {
}
}

资源:

@Component
@Path("/")
public class Hello {

@Secured
@GET
@Path("/hello")
public String test() {
    return "Hello!";
}
@GET
@Path("/world")
public String world() {
    return "World!";
}
}

【问题讨论】:

  • 试试this out
  • 非常感谢,请做出正确的答复,以便我选择您的答案。
  • 不如把它当作一个骗子来关闭 :-) 用例可能不一样,但原因是一样的。

标签: java spring spring-boot jersey jax-rs


【解决方案1】:

我假设您正在使用 Jersey API 来构建您的 RESTful 接口。您收到的 404 与(我认为)@Path(球衣)或@RequestMapping(春天)有关。

如果您发布更多与您的 API 路径相关的代码,那么我们可以提供进一步的帮助。

谢谢。

如果您查看顶级路径@Path("/")。您正在添加另一个正斜杠,因此 uri 最终看起来像:

http://localhost.com//hello http://localhost.com//world

要解决此问题,请从方法 @Path 注释中删除正斜杠,然后重新构建。这应该会导致 API 端点看起来像

http://localhost.com/hello http://localhost.com/world

【讨论】:

  • 这不是问题,两个端点都在工作,“world”方法正常返回字符串并且你好被过滤器拦截,问题是过滤器没有返回正确的响应,如果我删除过滤器“hello”方法上的if正常工作。 (弹簧靴可以带或不带额外的“/”,我刚刚测试过)。
  • 能否添加相关的过滤代码?
  • 已经在问题中了。
  • 为什么在没有任何反应的情况下验证令牌会抛出异常?
  • 我正在测试这种方法是否可行。
猜你喜欢
  • 2018-07-02
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多