简体   繁体   中英

Disabling HTTP GET/POST in Spring

I have a Spring application which is based on REST APIs. I would like to disable HTTP GET/POST methods but would like to allow HTTPS GET/POST methods.

How can I do that ?

Simply add the following to your application.properties :

server.port: 8443
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: password
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

Then generate a certificate to test

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

Add the keystore.p12 to src/main/resources so it is added to the jar

Here is an integration test via https:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

    @LocalServerPort
    private int port;

    private RestTemplate template;

    @Before
    public void setUp() throws Exception {
        createTemplateFromKeyStore("keystore.p12");
    }

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity("https://localhost:" + port + "/", String.class);
        assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
    }

    private void createTemplateFromKeyStore(String keyStoreName) {
        try {
            InputStream keyStoreInputStream = getClass().getResourceAsStream(keyStoreName);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(keyStoreInputStream, null);

            SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadKeyMaterial(keyStore, "password".toCharArray())
                    .loadTrustMaterial(keyStore, new TrustAllStrategy()).build();

            HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(httpClient);

            template = new RestTemplate(requestFactory);
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
}

Make your server only "HTTPS" enable and block "HTTP" request on server level. on application level HTTP request blocking is bad practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM