美文网首页
zuul 配置https(同时支持http跟https)

zuul 配置https(同时支持http跟https)

作者: 原始人y | 来源:发表于2020-07-18 09:21 被阅读0次

1 前言

最近几天刚开始接触微信小程序的开发,才接触到了https的概念(微信小程序中的请求必须为https请求,不然请求无法成功)。https算是对http的安全封装,在http的基础上加了ssl证书机制,此处不赘述,想要详细了解自行百度区别。所以博主就在考虑怎么让整个小程序后台(用的spring boot来作为后台)都能通过https访问,终于经过两天的研究,我发现了将ssl结合spring cloud的zuul(路由网关)可以实现我想要的效果,话不多说,上步骤。

2 申请域名,并用域名申请ssl证书(博主用的阿里申请的ssl证书)


image.png

点击下载,将对应的ssl证书下载到本地

3 创建zuul微服务

3.1pom.xml中配置相关依赖(需要添加到eureka注册中心)
     <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
  3.2 将ssl证书放到resources下的ssl文件夹中并在yml中配置


image.png

spring:
application:
name: zuul

注册到eureka

eureka:
instance:
lease-expiration-duration-in-seconds: 30
lease-renewal-interval-in-seconds: 10
prefer-ip-address: true
instance-id: dragon
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:7001/eureka/
server:
port: 443

ssl证书相关配置

ssl:
key-store: classpath:https/1538502410793.pfx
key-store-password: 1538502410793
key-store-type: PKCS12

zuul的相关配置

zuul:
routes:

需要配置路由的微服务

consumer:
  serviceId: eureka-consumer
  path: /con/**

无法使用服务名称访问

ignored-services: "*"

访问前添加前缀

prefix: /fengyuntec/

在网关 启动类添加如下代码:
@Value("${http.port:8888}")
private Integer port=8888;//http端口号

@Bean
public Connector connector(){//此函数中的80、443端口仅测试使用。 实际情况可读取配置后修改 <br>    
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setPort(port);
    connector.setSecure(false);
    connector.setRedirectPort(8889);//https端口号
    return connector;
}

@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
    TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
        @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(connector);
    return tomcat;
}

到此,这件事情就算是大功告成了。

但此时有同学可能会提出特殊的要求:
他的https只是为了某某的要求而使用的,比如说要接入什么什么的一定要填的是https的地址
而他的网站根本就不需要https这种安全级别的,另外,他觉得http的访问速度可能会快点,你知到有些同学是有这种洁癖的 :p
也就是说:
输入:my.com,跳到: http:// www.my.com
输入:https:// www.my.com,跳到:https:// www.my.com
要实现此要求,其实很简单,只需要把:

connector.setSecure(false);
改为

connector.setSecure(true);
...........
就大功告成了

相关文章

网友评论

      本文标题:zuul 配置https(同时支持http跟https)

      本文链接:https://www.haomeiwen.com/subject/folxkktx.html