Springboot 不允许通过 URL 中的百分比和反斜杠 [英] Springboot doesn't let through percentage and backslash in URL

查看:164
本文介绍了Springboot 不允许通过 URL 中的百分比和反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们收到了一个在 url 中发送字符串字符的 get 请求,因此我们使用路径变量来接收它们.显然,调用服务无法更改其调用后端的方法,因此我们需要能够接受包含以下未编码字符的网址:

We got a get request that sends string characters in url, so we use path variables to receive them. Apparently there is no way that the calling service would change its method of calling backend so we need to be able to accept a url with the following unencoded characters:

当发送百分号 % 时,会返回一个 http 400.如果 % 后面的两个字符组成一个 UTF 编码的字符,它就会通过

When percentage sign % is sent a http 400 is returned. It does go through if the two characters following % make up an UTF-encoded character

反斜杠转换为正斜杠.我需要它来保持反斜杠.

Backslash is converted into a forward slash. I need it to stay backslash.

我猜这些可能是 Tomcat 或 servlet 配置问题.

I'm guessing these might be Tomcat or servlet configuration issues.

(春季启动版本 1.5.14.RELEASE)

(spring boot version 1.5.14.RELEASE)

推荐答案

如果您正确地对百分比符号 (%) 进行 URL 编码 (%25),那么它们应该没有问题.但是,斜线和反斜线不适用于 Tomcat,即使您对它们进行编码(%2F%5C).

Percent signs (%) should be no problem if you properly URL encode them (%25). However, slashes and backslashes will not work with Tomcat, even if you encode them (%2F and %5C).

您可以在运行应用程序时设置以下属性:

You could set the following properties when running the application:

-Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
-Dorg.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true

然而,这不会解决问题,因为在这种情况下,那些编码的斜杠将被识别为真实的斜杠.因此,假设您有以下控制器:

However, this won't fix the issue, because in this case, those encoded slashes will be recognized as real ones. So, let's say you have the following controller:

@ResponseBody
@RequestMapping("/api/{foo}")
public String getFoo(@PathVariable String foo) {
    return foo;
}

好吧,那如果你调用/api/test%5Ctest,就找不到正确的路径了.此问题的解决方案是使用通配符匹配器并从传入的 HttpServletRequest 中解析 URL 本身:

Well, then if you call /api/test%5Ctest, it won't be able to find the correct path. A solution to this problem is to use wildcard matchers and to parse the URL itself from the incoming HttpServletRequest:

@RequestMapping("/api/**")
public String getFoo(HttpServletRequest request) {
    // ...
}

另一种解决方案是使用完全不同的 Web 容器.例如,在使用 Jetty 时,这根本不是问题,URL 编码的斜杠和反斜杠都可以使用.

Another solution is to use a completely different web container. For example, when using Jetty, this isn't a problem at all, and URL encoded slashes and backslashes will both work.

这篇关于Springboot 不允许通过 URL 中的百分比和反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆