httpservletrequest getrequesturi

i86rm4rw  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(361)

我有一个Spring Bootap。在控制器中使用此方法:

@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 ->/<- 与浏览器的结果相同。我想返回404作为所有不存在的Map localhost:7080 我试过:

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
6tqwzwtp

6tqwzwtp1#

它们应该已经被阻止,因为它们包含路径遍历。它们不是有效的请求。
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

zlhcx6iw

zlhcx6iw2#

我建议从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
    }
}

现在在控制器中,您只需通过以下语句获得确切的“called”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");
//}

相关问题