首页 > 代码库 > Jetty9 Embedded从http升级到https

Jetty9 Embedded从http升级到https

什么是https

之前我在这篇文章里头说过了https

造公钥和私钥

keytool -genkey -alias sitename -keyalg RSA -keystore keystore.jks -keysize 2048

这个文件是一个公钥和私钥对

创建Connector

这一点很关键,说白了,就是当发生http请求的时候,返回一个!403,告诉他不安全,让他重定向到安全的端口

具体的做法:

  1. 对于不安全的请求返回!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);
  1. 对于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;
    }
  2. 加入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;
    }
  3. 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