源码时代Java干货分享|手把手教你SpringBoot配置ssl证书

淡淡的烟草味﹌ 2023-06-25 07:48 73阅读 0赞

图说明
在这里插入图片描述
第一步首先去阿里云弄一个免费的SSL证书
在这里插入图片描述
下载然后 放到项目里面的resource路径下
这里一定要注意 是 key-store 和 key-store-password 我在配置时写出了 key-password 弄了很久没找到原因 换成了
nginx 去配置,最近还是嫌弃服务启动太多 改了回来
在这里插入图片描述
现在如果直接方法服务器上那么现在 就可以https 访问我的项目了 但是如果你用http 就不行 因为http是默认80端口 而https 是默认的 443 端口 所以我在我的启动类里面写一段代码 。防护http 是自动跳转到https
EmbeddedServletContainerFactory 可以因为你的spring boot 版本 过高没有这个class 那么你需要去你对应spring boot版本的class

  1. public class HuahaiApplication {
  2. public static void main(String[] args)
  3. {
  4. SpringApplication.run(HuahaiApplication.class, args);
  5. }
  6. /**
  7. * 配置一个 TomcatServletWebServerFactory bean
  8. * 将http 重定向到 https
  9. * @return
  10. */
  11. /**
  12. * it's for set http url auto change to https
  13. */
  14. @Bean
  15. public EmbeddedServletContainerFactory servletContainer(){
  16. TomcatEmbeddedServletContainerFactory tomcat=new TomcatEmbeddedServletContainerFactory(){
  17. @Override
  18. protected void postProcessContext(Context context) {
  19. SecurityConstraint securityConstraint=new SecurityConstraint();
  20. securityConstraint.setUserConstraint("CONFIDENTIAL");//confidential
  21. SecurityCollection collection=new SecurityCollection();
  22. collection.addPattern("/*");
  23. securityConstraint.addCollection(collection);
  24. context.addConstraint(securityConstraint);
  25. }
  26. };
  27. tomcat.addAdditionalTomcatConnectors(httpConnector());
  28. return tomcat;
  29. }
  30. //配置http转https
  31. @Bean
  32. public Connector httpConnector(){
  33. Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
  34. connector.setScheme("http");
  35. connector.setPort(80);
  36. connector.setSecure(false);
  37. connector.setRedirectPort(443);
  38. return connector;
  39. }
  40. }

最近我可以把我本地的服务映射到外网去访问借助一个 sunny-ngrok 免费的
在这里插入图片描述
去域名管理中心解析你的域名

在这里插入图片描述
本地启动ngrok 的服务
在这里插入图片描述
效果
输入你的域名 不大https 也会自动跳转到https 这里是因为我刚刚在启动类里面配置了 重定向
在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,73人围观)

还没有评论,来说两句吧...

相关阅读