SpringBoot添加HTTPS支持

证书生成

使用SSL需要我们先生成一个证书,这个证书我们可以自己生成,也可以从SSL证书授权中心获得。

命令生成证书

生成JKS证书

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 1024 -validity 365 -keystore keystore.jks -keypass 123456 -storepass 123456

生成P12证书

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -validity 365 -keystore keystore.p12

-alias 别名
-keypass 指定生成密钥的密码
-keyalg 指定密钥使用的加密算法(如 RSA)
-keysize 密钥大小
-validity 过期时间,单位天
-keystore 指定存储密钥的密钥库的生成路径、名称
-storepass 指定访问密钥库的密码

修改配置文件

 将证书文件添加到resources目录,并修改application.properties

server.port=443
server.http-port=80

#开启https,配置跟证书一一对应
server.ssl.enabled=true
#指定证书
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-type=JKS
#server.ssl.key-store=classpath:keystore.p12
#server.ssl.key-store-type= PKCS12
#别名
server.ssl.key-alias=tomcat
#密码
server.ssl.key-password=123456
server.ssl.key-store-password=123456
  • key-store:生成的证书文件的存储路径

  • key-store-password:指定签名的密码,要设置成刚刚你设置的密码

  • keyStoreType:为制定秘钥仓库的类型(PKCS12或者JKS)

  • keyAlias: 别名

如果不知道别名,可以在服务器中输入

keytool -list -keystore keystore.p12

配置http重定向https

在入口类中添加相应的转向Bean

@SpringBootApplication
public class TestDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestDemoApplication.class, args);
    }

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(80);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(443);
        return connector;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中实现HTTPS,你需要做以下几个步骤: 1. 生成SSL证书:首先,你需要生成一个SSL证书,用于加密和验证HTTPS连接。你可以使用工具如OpenSSL来生成自签名证书,或者购买一个由公共CA(Certificate Authority)签名的证书。 2. 配置Spring Boot应用程序:在Spring Boot应用程序的配置文件中,你需要指定HTTPS相关的配置。这包括端口号、SSL证书和密钥的位置等信息。 ```properties server.port=8443 server.ssl.key-store-type=JKS server.ssl.key-store=classpath:keystore.jks server.ssl.key-store-password=password server.ssl.key-alias=myapp ``` 你可以根据自己的证书和密码进行配置。 3. 启用HTTPS支持:在Spring Boot应用程序的入口类上添加`@EnableWebSecurity`和`@Configuration`注解,创建一个配置类来启用HTTPS支持。 ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.header.HeaderWriterFilter; import org.springframework.security.web.header.writers.StaticHeadersWriter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.util.StreamUtils; import javax.servlet.Filter; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.nio.charset.StandardCharsets; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("${server.ssl.key-store-password}") private String keyStorePassword; @Value("${server.ssl.key-alias}") private String keyAlias; @Override protected void configure(HttpSecurity http) throws Exception { http.requiresChannel().anyRequest().requiresSecure(); http.csrf().disable(); http.headers().addHeaderWriter( new StaticHeadersWriter(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "authorization,cache-control,content-type")); http.headers().addHeaderWriter( new StaticHeadersWriter(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD,POST,PUT,DELETE,OPTIONS")); http.headers().addHeaderWriter( new StaticHeadersWriter(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")); http.headers().addHeaderWriter( new StaticHeadersWriter(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); http.addFilterAfter(new CustomFilter(), HeaderWriterFilter.class); } private Filter customFilter() { return new CustomFilter(); } private class CustomFilter extends UsernamePasswordAuthenticationFilter { @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { // Your custom logic here } } } ``` 这个配置类将启用HTTPS,并配置了一些安全相关的设置,如禁用CSRF保护、允许跨域请求等。 4. 运行应用程序:启动Spring Boot应用程序,并通过HTTPS访问应用程序的URL,例如`https://localhost:8443`。 这样,你的Spring Boot应用程序就会通过HTTPS进行安全的通信了。请注意,为了使SSL证书生效,你需要将证书文件(例如`keystore.jks`)放置在类路径下,或者在配置文件中指定正确的证书路径。 希望这些步骤对你有帮助!如果有任何疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值