To be able to redirect all requests from HTTP to HTTPS in your Spring Boot application make sure that you have org.springframework.boot:spring-boot-starter-security
as a dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Assuming you managed to setup your SSL certificates. Most likely you get SSL sertificates from your hosting provider like Heroku or any other.
WebSecurityConfigurerAdapter
Now you need to create that configuration in your project.
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().requiresSecure();
}
}
To be able to run the application locally and use HTTP just add this to that config .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.
This just checks that it’s not behind the proxy.
CSRF
Remember, by default in Spring Boot CSRF Security is enabled so if you don’t care about CSRF tokens only GET requests will be allowed.
POST, PUT and DELETE will cause 403s.
So if you don’t need CSRF Security then disable it with http.csrf().disable();
The complete configuration will look like that
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.requiresChannel()
.requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
}
}