標籤:blog http io ar os sp java for on
什麼是https
之前我在這篇文章裡頭說過了https
造公開金鑰和私密金鑰
keytool -genkey -alias sitename -keyalg RSA -keystore keystore.jks -keysize 2048
這個檔案是一個公開金鑰和私密金鑰對
建立Connector
這一點很關鍵,說白了,就是當發生http請求的時候,返回一個!403,告訴他不安全,讓他重新導向到安全的連接埠
具體的做法:
- 對於不安全的請求返回!403
其實這個是加到web.xml裡頭的,只是這裡用代碼展現出來
ConstraintSecurityHandler security = new ConstraintSecurityHandler();Constraint constraint = new Constraint();constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);//makes the constraint apply to all uri pathsConstraintMapping mapping = new ConstraintMapping();mapping.setPathSpec("/*");mapping.setConstraint(constraint);security.addConstraintMapping(mapping);// Web app handlersWebAppContext app = new WebAppContext(server, base, "/");app.setHandler(security);
-
對於http的Connector,告訴它安全的連接埠和協議是什麼
private static ServerConnector getHttpConnector(int port) {HttpConfiguration config = new HttpConfiguration();config.setSecureScheme("https");config.setSecurePort(port + 443);ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(config));connector.setPort(port);return connector;}
-
加入https的Connector
private static ServerConnector getHttpsConnector(int port) {HttpConfiguration https = new HttpConfiguration();https.setSecurePort(port);https.setSecureScheme("https");https.addCustomizer(new SecureRequestCustomizer());SslContextFactory sslContextFactory = new SslContextFactory();sslContextFactory.setKeyStorePath(ControllerWebServer.class.getResource( "/keystore.jks").toExternalForm());sslContextFactory.setKeyStorePassword("123456");sslContextFactory.setKeyManagerPassword("123456");ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));sslConnector.setPort(port);return sslConnector;}
-
server 啟動
server.setConnectors(new Connector[]{httpsConnector, httpConnector});// Web app handlersWebAppContext app = new WebAppContext(server, base, "/");app.setHandler(security);// Start appserver.start();logger.info(LoggerServer.CU, "Start updater web server success");server.join();
Jetty9 Embedded從http升級到https