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;
}
  1. 加入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;
}
  1. 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();

转载于:https://my.oschina.net/zuoyc/blog/352379

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值