spring boot 中启用 https

获取证书

https 是加密链接. 是需要证书的. 那么证书从哪里取得呢? 在本地测试的时候, 可以自己生成一个 tomcat 的证书, 可以本地测试用.

生成方式配置方式见下面

tool -genkey -v -alias mykey -keyalg RSA -validity 3650 -keystore ./keystore

在yml配置如下

server.port:8443
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: xxxxx
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

但是本地生成的证书在生产环境是没法用的. 第三方调用的时候是不 OK 的.
于是, 在阿里云上找到了免费的证书申请.

购买后, 会有邮件发到注册邮箱来认证的. 当然, 这里要注意这个免费的证书只能用在一个域名下.
(不知道为什么用公司邮箱和个人邮箱, 这里给出的认证方式不同. )

spring boot 配置

证书生成好之后, 下载之. 然后放在resources目录下. 和 application.properties 并列.

阿里云这个下载下来默认是pfx 格式的. 按照下面这样配置就行:

server.ssl.key-store=classpath:1111111.pfx
server.ssl.key-store-password=1111111
server.ssl.keyStoreType=PKCS12  

因为是生产环境, 需要做 http 自动转到 https. 所以这里不配置端口号.

http 自动转到 https

生产环境上 http 转到 https 是一个很必要的能力. 在 spring boot 的启动类中. 添加如下代码即可 ```

package wang.vchen.handling.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @Auther Vchen
 * @Description:
 * @Date: 20:56 2017/6/20.
 * @Modified:
 */
@Configuration
public class HttpsConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(){//1
            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(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);//表示用8080端口来供http访问
        connector.setSecure(false);
        connector.setRedirectPort(8090);//自动重定向到8090端口
        return connector;
    }
}

这样就可以实现 HTTPS 了

如果是测试环境的证书,浏览器可能会拦截,说是不安全的,需要将浏览器设置一下。

 

转载于:https://my.oschina.net/kingchen8080/blog/994367

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值