码迷,mamicode.com
首页 > Web开发 > 详细

Jetty9 Embedded从http升级到https

时间:2014-12-04 20:10:20      阅读:187      评论:0      收藏:0      [点我收藏+]

标签: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,告诉他不安全,让他重定向到安全的端口

具体的做法:

  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

标签:blog   http   io   ar   os   sp   java   for   on   

原文地址:http://my.oschina.net/zuoyc/blog/352379

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!