How to add self signed SSL certificate to jHipster

2019-01-12 23:22发布

I have create sample jHipster app. Now I want to add self signed SSL certificate and test in local to have a access to https. How to achieve this?

3条回答
Juvenile、少年°
2楼-- · 2019-01-13 00:01

These instructions are applicable for all Spring Boot applications, on which JHipster is based. I have tested this on a newly generated JHipster 2.7 project.

You need to complete these steps when starting from scratch:

  1. Generate a self-signed certificate
  2. Add the SSL properties to your application.properties or application.yml as mentioned in the Spring Boot documentation
  3. (Optional) Redirect HTTP to HTTPS

Generating a self-signed certificate

First you need to generate your self-signed certificate in your project directory, this can be done with keytool, which is utility script provided by Java:

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Enter keystore password:  
Re-enter new password:
What is your first and last name?
  [Unknown]:  
What is the name of your organizational unit?
  [Unknown]:  
What is the name of your organization?
  [Unknown]:  
What is the name of your City or Locality?
  [Unknown]:  
What is the name of your State or Province?
  [Unknown]:  
What is the two-letter country code for this unit?
  [Unknown]:  
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
  [no]:  yes

I have chosen password mypassword so this is the one I will use in the next step. When you have done this, you will see a keystore.p12 in your current directory.

Add the SSL properties to your application.properties or application.yml as mentioned in the Spring Boot documentation

Now you need to add the HTTPS connector properties for Tomcat. You can find the property (yml) files in src/main/resources/ and you need to update the application.yml (or if it is only for development in application-dev.yml with the following properties:

server:
  ssl:
    key-store: keystore.p12
    key-store-password: mypassword
    keyStoreType: PKCS12
    keyAlias: tomcat

Now you can package your application with Maven (or Gradle if you chose that for your JHipster application) using mvn clean package and run the application using mvn spring-boot:run. You can now access your application on https://localhost:8080

For simplicity I did not change the port, but ideally you should change it as well in the properties files, but I left it out since they are already defined in application-dev.yml and application-prod.yml so you would have to change it in there or remove it and put it in the general application.yml


(Optional) Add redirect HTTP to HTTPS

You can only enable one protocol through the application.properties, so when you do this like above only HTTPS will work. If you want HTTP to work too, and redirect to HTTPS you have to add a @Configuration class like below

@Bean
  public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new      TomcatEmbeddedServletContainerFactory() {
        @Override
        protected void postProcessContext(Context context) {
          SecurityConstraint securityConstraint = new SecurityConstraint();
          securityConstraint.setUserConstraint("CONFIDENTIAL");
          SecurityCollection collection = new SecurityCollection();
          collection.addPattern("/*");
          securityConstraint.addCollection(collection);
          context.addConstraint(securityConstraint);
        }
      };

    tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
    return tomcat;
  }

  private Connector initiateHttpConnector() {
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setPort(8080);
    connector.setSecure(false);
    connector.setRedirectPort(8443);

    return connector;
  }

This response is basically a copy of my blog post on the same subject: http://www.drissamri.be/blog/java/enable-https-in-spring-boot/

查看更多
走好不送
3楼-- · 2019-01-13 00:12

To extend the Driss Amri brilliant answer on how to re-enable BrowserSync.

If you choose not to support http, or if http is redirected to https, BrowserSync will not work. To make it work again, few changes are necessary in:

  1. gulp/config.js, apiPort and uri to:

    apiPort: 8443, 
    uri: 'https://localhost:',
    
  2. gulp/serve.js: add options.rejectUnauthorized = false; into proxyRoutes so that node does not complain about self signed certificate:

    proxyRoutes.map(function (r) {
        var options = url.parse(baseUri + r);
        options.route = r;
        options.preserveHost = true;
        options.rejectUnauthorized = false;
        return proxy(options);
    }));
    
  3. optionally let BrowserSync serve content over https too. I recommend it with Spring Social to save some trouble. Just add https: true into browserSync call in gulp/serve.js:

    browserSync({
        open: true,
        port: config.port,
        server: {
            baseDir: config.app,
            middleware: proxies
        },
        https: true
    });
    

    Now BrowserSync will serve content with self signed certificate shipped with it. It is possible to reuse the one created for Spring Boot, more on BrowserSync homepage.

查看更多
爷的心禁止访问
4楼-- · 2019-01-13 00:17

For those using webpack instead of gulp you can complete Driss Amri's answer with two changes:

modify the proxy.conf.json:

{
    "*": {
        "target": "https://localhost:8443",
        "secure": true
    }
}

this will redirect API requests to the new https address. Then alter also webpack file for instance here a webpack.dev.js modified example:

module.exports = webpackMerge(commonConfig({ env: ENV }), {
devtool: 'eval-source-map',
devServer: {
    contentBase: './target/www',
    proxy: [{
        context: [
            /* jhipster-needle-add-entity-to-webpack - JHipster will add entity api paths here */
            '/api',
            '/management', ...
            '/auth'
        ],
        target: 'https://127.0.0.1:8443',
        /* set secure to false here, otherwise self-signed certification cause DEPTH_ZERO_SELF_SIGNED_CERT proxy errors */
        secure: false
    }]
},
查看更多
登录 后发表回答