我正在开发一个春季启动应用程序,我跟着这个reply, 这一切都很好,尽管需要一些调整才能使它在弹簧启动时工作,但问题是我打电话时:
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!";
}
}
答案 0 :(得分:0)
我假设您使用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