标签:blog http io ar os sp java for on
之前我在这篇文章里头说过了https
keytool -genkey -alias sitename -keyalg RSA -keystore keystore.jks -keysize 2048
这个文件是一个公钥和私钥对
这一点很关键,说白了,就是当发生http请求的时候,返回一个!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();
标签:blog http io ar os sp java for on
原文地址:http://my.oschina.net/zuoyc/blog/352379