我有一个基于REST API的Spring应用程序。我想禁用HTTP GET / POST方法,但希望允许HTTPS GET / POST方法。
我该怎么做?
答案 0 :(得分:4)
只需将以下内容添加到您的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
然后生成要测试的证书
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
将keystore.p12添加到src / main / resources,以便将其添加到jar
以下是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);
}
}
}
答案 1 :(得分:0)
仅限您的服务器&#34; HTTPS&#34;启用和阻止&#34; HTTP&#34;服务器级请求。在应用程序级别上,HTTP请求阻止是不好的做法。