티스토리 뷰

Spring Boot에서 임베디드 톰켓 서버를 이용할때 디폴트 서버로 HTTP 또는 HTTPS를 선택해야 합니다. 

아래는 HTTP로 접속 할 경우 HTTPS로 전환 시켜주는 방법입니다. 




1. 먼저 SSL 증명서를 발급 받아야 합니다. 

HTTPS연동을 위해서 우선 keystore를 만들어야 합니다. 


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

Enter keystore password:
 Re-enter new password:
 What is your first and last name?
 [Unknown]:
 What is the name of your organizational unit?
 [Unknown]:
 What is the name of your organization?
 [Unknown]:
 What is the name of your City or Locality?
 [Unknown]:
 What is the name of your State or Province?
 [Unknown]:
 What is the two-letter country code for this unit?
 [Unknown]:
 Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
 [no]: yes


2. 스프링 부트 내에서 HTTPS가 가능하도록 설정합니다. 

스프링 부트는 src/main/resources 폴더 내에 위치한 application.properties 파일에서 필요한 설정들을 할 수 있습니다. 아래와 같이 설정 할 경우, https://localhost:8443으로 접속할 수 있습니다. 

#ssl
server.ssl.key-store=classpath:path위치
server.ssl.key-store-password=password
server.ssl.key-password=password
server.port=8443
server.port.http=8080


3. HTTP로 접속할 경우, HTTPS로 리다이렉트(전환) 시켜줍니다. (@Configuration클래스내에)

@Configuration
@EnableConfigurationProperties
public class SampleConfig {


@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat =
new TomcatEmbeddedServletContainerFactory() {

@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(createHttpConnector());
return tomcat;
}

@Value("${server.port.http}")
private int serverPortHttp;

@Value("${server.port}")
private int serverPortHttps;

private Connector createHttpConnector() {
Connector connector =
new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(serverPortHttp);
connector.setRedirectPort(serverPortHttps);
return connector;
}


}



전체 소스 코드는 https://github.com/annajinee/Spring-Boot-redirect-HTTP-to-HTTPS 에서 확인 가능합니다. 




참고 사이트 : https://drissamri.be/blog/java/enable-https-in-spring-boot/

     http://williewheeler.com/2015/03/25/redirecting-http-to-https-in-spring-boot/


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함