I’m using spring-data-rest in my application which is behind apache reverse proxy that redirects from HTTP to HTTPS
This in turn leads to wrong hrefs: http
instead https
scheme.
Example:
{
"_links" : {
"profile" : {
"href" : "http://my.host/api/profile"
}
}
}
Is there any way I can configure spring.data.rest
to force use https scheme?
Redirect HTTP requests to HTTPS To do that in spring boot, we need to add HTTP connector at 8080 port and then we need to set redirect port 8443 . So that any request in 8080 through http, it would be automatically redirected to 8443 and https.
To enable support for HTTP and HTTPS in Spring Boot 2, we need to register an additional connector with Spring Boot application. First, enable SSL/HTTPS for Spring Boot, for example by following the HTTPS using Self-Signed Certificate in Spring Boot tutorial. Now, add server. http.
Spring Boot helps developers create applications that just run. Specifically, it lets you create standalone applications that run on their own, without relying on an external web server, by embedding a web server such as Tomcat or Netty into your app during the initialization process.
After digging in the source code, I found out that all link creations originates from this point and it seems to be impossible to configure forced use of https scheme in a 'standard' way.
So I created a filter that replaces http://
to https://
in request URL and the problem has gone. Here is the snippet:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) {
@Override
public StringBuffer getRequestURL() {
final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
final String updatedUrl = originalUrl.toString().replace("http://", "https://");
return new StringBuffer(updatedUrl);
}
};
filterChain.doFilter(wrapped, servletResponse);
}
I was having the same problem and it is all the answers those helped me to find a simple solution in 2 steps :
I added configuration in my spring-data-rest v2.5.4
application to use X-Forwarded-*
headers
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ForwardedHeaderFilter;
@Configuration()
public class ApiConfiguration {
@Bean()
ForwardedHeaderFilter forwardedHeaderFilter() {
return new ForwardedHeaderFilter();
}
}
I added comfiguration to my proxy (nginx v1.20.0
) to forward scheme
, host
and port
location /api {
proxy_pass http://localhost:8080;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
Hope that it will help next ones
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With