当前位置: 首页 > news >正文

总结:如何在SpringBoot中使用https协议以及自签证书?

总结:如何在SpringBoot中使用https协议以及自签证书?

  • 前提一:什么是http协议?
  • 前提二:什么是https协议?
  • 一·生成自签证书
  • 二· 将证书转换为PKCS12格式
  • 三· 配置SpringBoot
    • (1)修改配置文件:application.properties或application.yml
    • (2) 配置HTTP重定向到HTTPS(可选)
    • (3)控制器示例代码:
    • (4)完整项目结构
  • 四·验证成功
    • (1)启动Spring Boot应用:
    • (2)处理浏览器警告
    • (3)使用https协议访问:https://localhost:8443/hello(浏览器会提示证书不安全,点击“继续”即可)。
    • (4)使用http协议访问:http://localhost:8080/hello,会自动跳转到HTTPS(如果配置了HTTP重定向)
    • (5)使用Java代码发起https请求验证:成功!
    • (6)https工具类代码地址:

前提一:什么是http协议?

https://t4dmw.blog.csdn.net/article/details/123313047

前提二:什么是https协议?

https://t4dmw.blog.csdn.net/article/details/123385750

一·生成自签证书

使用OpenSSL生成自签证书(如果已有证书可跳过此步骤):

openssl req -x509 -newkey rsa:4096 -keyout private_key.pem -out public_cert.pem -days 365 -nodes

生成的文件:

private_key.pem:私钥文件。

public_cert.pem:证书文件,包含公钥。

在这里插入图片描述
在这里插入图片描述

二· 将证书转换为PKCS12格式

Spring Boot需要PKCS12格式的证书文件(.p12或.pfx)。使用以下命令转换:

openssl pkcs12 -export -in public_cert.pem -inkey private_key.pem -out keystore.p12 -name "mycert"

输入密码:设置证书库密码(如123456)生成keystore.p12文件。
在这里插入图片描述

三· 配置SpringBoot

将证书文件(keystore.p12)复制到Spring Boot项目的src/main/resources目录下。

(1)修改配置文件:application.properties或application.yml

server:
  ssl:
    # 开启ssl
    enabled: true
    # keystore文件
    key-store: classpath:keystore.p12
    # keystore格式
    key-store-type: PKCS12
    # keystore密码
    key-store-password: 123456
    # keystore别名
    key-alias: mycert
  # https端口
  port: 8443

(2) 配置HTTP重定向到HTTPS(可选)

如果希望所有HTTP请求自动重定向到HTTPS,可以添加以下配置,HTTP端口在代码中设置为8080

(2-1) 添加Tomcat配置类

package com.example.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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liumingfu
 * @date 2020/06/08 22:06
 * @description: https配置
 */
@Configuration
public class HttpsConfig {

    @Bean
    public ServletWebServerFactory servletContainer() {
        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);
            }
        };

        // 添加HTTP连接器,重定向到HTTPS
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    /**
     * 访问http协议8080端口,重定向到https协议8443端口
     *
     * @param
     * @return
     * @author LiuMingFu
     * @date 2025/2/14
     */
    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);  // HTTP端口
        connector.setSecure(false);
        connector.setRedirectPort(8443);  // HTTPS端口
        return connector;
    }
}

(3)控制器示例代码:

控制层

package com.example.controller;

import com.example.service.MyService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description TODO
 * @Author LiuMingFu
 * @Date 2025/2/13 17:58
 */
@RestController
public class MyController {
    
    @Resource
    private MyService myService;
    
    
    @RequestMapping("/hello")
    public String getHello(){
        return myService.getHello();
    }
}

service接口层

package com.example.service;

import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Author LiuMingFu
 * @Date 2025/2/13 18:00
 */
@Service
public interface MyService {
    String getHello();
}

service接口实现层

package com.example.service.impl;

import com.example.service.MyService;
import org.springframework.stereotype.Repository;

/**
 * @Description TODO
 * @Author LiuMingFu
 * @Date 2025/2/13 18:00
 */
@Repository
public class MyServiceImpl implements MyService {
    @Override
    public String getHello() {
        return "hello https";
    }
}

(4)完整项目结构

在这里插入图片描述

四·验证成功

(1)启动Spring Boot应用:

在这里插入图片描述

在这里插入图片描述

(2)处理浏览器警告

  • 自签证书会导致浏览器显示“不安全”警告。在开发环境中,可以手动信任证书:
  • 将public_cert.pem导入浏览器或操作系统的信任库。
  • 对于测试工具(如Postman或curl),添加-k或–insecure参数忽略证书验证。

(3)使用https协议访问:https://localhost:8443/hello(浏览器会提示证书不安全,点击“继续”即可)。

在这里插入图片描述

(4)使用http协议访问:http://localhost:8080/hello,会自动跳转到HTTPS(如果配置了HTTP重定向)

在这里插入图片描述
在这里插入图片描述

(5)使用Java代码发起https请求验证:成功!

注意:使用代码方式,访问的接口域名,必须跟证书的域名地址一致,否则报错
在这里插入图片描述

(6)https工具类代码地址:

https://blog.csdn.net/weixin_48033662/article/details/145640901

相关文章:

  • DeepSeek模型架构及优化内容
  • C++ 标准库常见容器
  • Kotlin 2.1.0 入门教程(十六)属性、getter、setter、幕后字段、后备属性、编译时常量、延迟初始化
  • 【网络法医】恶意软件分析
  • 国内外网络安全政策动态(2025年1月)
  • mysql中general_log日志详解
  • mysql索引为什么用B+树,不用二叉树
  • Spring系统学习——持续更新
  • MySQL的备份与还原
  • 项目BUG
  • 股指期货有什么常见的交易方式?
  • ChatGPT macOS 桌面应用让你的编程体验更上一层楼
  • AI问答-供应链管理-M2:战略分析模型汇总
  • spring boot单元测试
  • LeetCode刷题第7题【整数反转】---解题思路及源码注释
  • 网络基础 【UDP、TCP】
  • 什么是耐环境环形光源
  • 企业文件共享中的权限管理与安全风险防范
  • 蓝桥杯篇---实时时钟 DS1302
  • 传输层协议TCP (上)
  • 网站专题页面案例/seo服务收费
  • 营销型网站公司排名/广州网站定制多少钱
  • wordpress免登录支付/上海专业的seo公司
  • 软件开发的阶段/济南seo顾问
  • 灵山招聘网灵山英才网做灵山专业的招聘网站/拉新app推广平台
  • 国外电子政务j建设与我国电子政务网站建设对比/品牌整合营销推广