【问题标题】:HttpServletRequest getRequestURI in SpringBootSpring Boot 中的 HttpServletRequest getRequestURI
【发布时间】:2021-05-14 00:54:28
【问题描述】:

我有一个 SpringBoot 应用程序。在控制器中使用此方法:

@GetMapping(value = "/")
public String home(Model model, HttpServletRequest request) {
    System.out.println("home ->" + request.getRequestURI() + "<-");
}

但是当我从控制台执行时:

curl localhost:7080
curl localhost:7080/./
curl localhost:7080/../
curl localhost:7080/..

我总是得到相同的结果:home -&gt;/&lt;-

和浏览器的结果相同。我想为所有不是localhost:7080的映射返回404

我试过了:

MacBook-Pro-de-nunito:~ nunito$ curl --path--as-is localhost:7080/./
curl: option --path--as-is: is unknown
curl: try 'curl --help' or 'curl --manual' for more information


 curl --version
curl 7.64.1 (x86_64-apple-darwin20.0) libcurl/7.64.1 (SecureTransport) LibreSSL/2.8.3 zlib/1.2.11 nghttp2/1.41.0
Release-Date: 2019-03-27
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp 
Features: AsynchDNS GSS-API HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM NTLM_WB SPNEGO SSL UnixSockets

【问题讨论】:

  • 好的。有问题吗?
  • 有没有办法为所有与 / 不同的映射返回 404?
  • 抱歉标志中的拼写错误,请使用curl --path-as-is localhost:7080/./。我不小心在as 之前添加了额外的-

标签: java spring spring-boot spring-mvc spring-security


【解决方案1】:

这些应该已经被阻止,因为它们包含路径遍历。它们不是有效的请求。

Curl 在发送到 spring 之前会修改它们,就像浏览器一样。您可以使用--path-as-is 标志来指示 curl 按原样发送 url。

类似

curl --path-as-is localhost:7080/./

执行此操作后,您应该会收到带有 RequestedRejectedException 的内部服务器错误。

有开放的jira默认将其更改为400 - https://github.com/spring-projects/spring-security/issues/7568

【讨论】:

    【解决方案2】:

    我建议从 3PP 图书馆寻求帮助。下面的例子

    <dependency>
      <groupId>org.zalando</groupId>
      <artifactId>logbook-spring-boot-starter</artifactId>
      <version>2.4.1</version>
    </dependency>
    

    并添加一个类,在请求到达实际控制器之前将正确的完整 URL 放入请求范围

    public class LogbookSink implements Sink {
    
        @Override
        public void write(final Precorrelation precorrelation, final HttpRequest request) throws IOException {
            request.setAttribute("complete_url", request.getRequestUri());
        }
    
        @Override
        public void write(final Correlation correlation, final HttpRequest request, final HttpResponse response) throws IOException {
            //do something else for response
        }
    }
    

    现在在控制器中,您可以通过说简单地获取确切的“被调用”URI

    String calledUri = request.getAttribute("complete_url");
    //your logic to throw 404
    //if (!calledUri.matches("localhost:7080/")){
    //    throw new ResponseStatusException(NOT_FOUND, "Unable to find resource");
    //}
    

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2015-10-05
      • 2022-12-22
      相关资源
      最近更新 更多