74

I wrote a servlet in Java and I would like to know if the request to that servlet was executed using HTTP or HTTPS.

I thought I can use request.getProtocol() but it returns HTTP/1.1 on both methods.

Any ideas?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
ufk
  • 30,912
  • 70
  • 235
  • 386

3 Answers3

103

HttpSerlvetRequest.isSecure() is the answer. The ServletContainer is responsible for returning true in the following cases:

  • If the ServletContainer can itself accept requests on https.
  • If there is a LoadBalancer in front of ServletContainer. And , the LoadBlancer has got the request on https and has dispatched the same to the ServletContainer on plain http. In this case, the LoadBalancer sends X-SSL-Secure : true header to the ServletContainer, which should be honored.

The Container should also make this request attributes available when the request is received on https:

  • javax.servlet.http.sslsessionid
  • javax.servlet.request.key_size
  • javax.servlet.request.X509Certificate
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • 3
    Can you please share where did you get 'X-SSL-Secure : true' bit? I keep searching and I cannot find more info on this header. – zbstof Sep 19 '16 at 12:56
  • 1
    This does not work on my environment: Apache 2.4.10 as front proxy; it iseems to be impossible to know in java, wheter the request has been done with http or https to apache. Sure, I get it as http to Java, but I need to know, how the front proxy has been accessed. - Indeed, as @Zotov also mentioned: There is almost no info about X-SSL-Sercure header. So I assume this is not widly implemented?! – badera Aug 19 '17 at 07:49
  • The header name may differ since it is not very standard. But, the concept here is that the proxies can add headers about the SSL and the servers can read them. For Ex, Nginx adds X-SSL-Protocol. It can replaced with custom header also. – Ramesh PVK Aug 21 '17 at 23:15
  • I guess, you use any specific Load Balancer as f5 and the "X-SSL-Secure : true" is an optional header, which is not part of any (even not load balancer) standard, right? – Marek-A- Apr 14 '20 at 16:16
29

You can't reliably depend on port numbers.
But you can depend on the scheme:

Use: request.getScheme() to see if it is https.

If it is then it is secure connection.

I believe this should work regardless of Tomcat version

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • 1
    isSecure goes back to at least [1.2](http://download.oracle.com/javaee/1.2.1/api/javax/servlet/ServletRequest.html#isSecure%28%29), and is not Tomcat-specific. – Matthew Flaschen Nov 21 '11 at 02:11
11

isSecure. Be sure to check the inherited methods.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539