首页 > 代码库 > Jetty9 Embedded从http升级到https
Jetty9 Embedded从http升级到https
什么是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 paths ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); mapping.setConstraint(constraint); security.addConstraintMapping(mapping); // Web app handlers WebAppContext 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 handlers WebAppContext app = new WebAppContext(server, base, "/"); app.setHandler(security); // Start app server.start(); logger.info(LoggerServer.CU, "Start updater web server success"); server.join();
Jetty9 Embedded从http升级到https
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。