天天看點

Springboot以Tomcat為容器實作http重定向到https的兩種方式

Springboot以Tomcat為容器實作http重定向到https的兩種方式

1 簡介

本文将介紹在Springboot中如何通過代碼實作Http到Https的重定向,本文僅講解Tomcat作為容器的情況,其它容器将在以後一一道來。

建議閱讀之前的相關文章:

(1) Springboot整合https原來這麼簡單

(2)HTTPS之密鑰知識與密鑰工具Keytool和Keystore-Explorer

2 相關概念

2.1 什麼叫重定向

所謂重定向,就是本來你想浏覽位址A的,但是到達服務端後,服務端認為位址A的界面不在了或者你沒權限通路等原因,不想你通路位址A;就告訴你另一個位址B,然後你再去通路位址B。

對于重定向一般有兩個傳回碼:

301:永久性重定向;

302:暫時性重定向。

通過Chrome檢視網絡詳情,記錄了幾個網站的重定向情況:

網站 域名 重定向代碼 重定向後的網址

南瓜慢說 www.pkslow.com 301

https://www.pkslow.com Google www.google.com 307 https://www.google.com Apple www.apple.com 307 https://www.apple.com 支付寶 www.alipay.com 301 https://www.alipay.com QQ www.qq.com 302 https://www.qq.com 百度 www.baidu.com 307 https://www.baidu.com

注:307也是重定向的一種,是新的狀态碼。

2.2 為什麼要重定向

結合我上面特意列的表格,是不是大概想到了為何要做這種重定向?不難發現上面的重定向都在做一件事,就是把http重定向為https。原因如下:

(1)http是不安全的,應該使用安全的https網址;

(2)但不能要求使用者每次輸入網站都輸入

https://

 吧,這也太麻煩了,是以大家都是習慣于隻輸入域名,甚至連www. 都不願意輸入。是以,使用者的輸入其實都是通路http的網頁,就需要重定向到https以達到安全通路的要求。

2.3 如何做到重定向

首先,伺服器必須要同時支援http和https,不然也就沒有重定向一說了。因為https是必須提供支援的,那為何還要提供http的服務呢?直接通路https不就行了,不是多此一舉嗎?原因之前已經講過了,大家是習慣于隻輸入簡單域名通路的,這時到達的就是http,如果不提供http的支援,使用者還以為你的網站已經挂了呢。

兩種協定都提供支援,是以是需要打開兩個Socket端口的,一般http為80,而https為443。然後就需要把所有通路http的請求,重定向到https即可。不同的伺服器有不同的實作,現在介紹Springboot+Tomcat的實作。

3 Springboot Tomcat實作重定向

Springboot以Tomcat作為Servlet容器時,有兩種方式可以實作重定向,一種是沒有使用Spring Security的,另一種是使用了Spring Security的。代碼結構如下:

主類的代碼如下:

package com.pkslow.ssl;

import com.pkslow.ssl.config.containerfactory.HttpToHttpsContainerFactoryConfig;

import com.pkslow.ssl.config.security.EnableHttpWithHttpsConfig;

import com.pkslow.ssl.config.security.HttpToHttpsWebSecurityConfig;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Import;

@SpringBootApplication

@Import({EnableHttpWithHttpsConfig.class, HttpToHttpsWebSecurityConfig.class})

//@Import(HttpToHttpsContainerFactoryConfig.class)

@ComponentScan(basePackages = "com.pkslow.ssl.controller")

public class SpringbootSslApplication {

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

}

@ComponentScan(basePackages = "com.pkslow.ssl.controller"):沒有把config包掃描進來,是因為想通過@Import來控制使用哪種方式來進行重定向。當然還可以使用其它方式來控制,如@ConditionalOnProperty,這裡就不展開講了。

當沒有使用Spring Security時,使用@Import(HttpToHttpsContainerFactoryConfig.class);

當使用Spring Security時,使用@Import({EnableHttpWithHttpsConfig.class, HttpToHttpsWebSecurityConfig.class})。

配置檔案application.properties内容如下:

server.port=443

http.port=80

server.ssl.enabled=true

server.ssl.key-store-type=jks

server.ssl.key-store=classpath:localhost.jks

server.ssl.key-store-password=changeit

server.ssl.key-alias=localhost

需要指定兩個端口,server.port為https端口;http.port為http端口。注意在沒有https的情況下,server.port指的是http端口。

3.1 配置Container Factory實作重定向

配置的類為HttpToHttpsContainerFactoryConfig,代碼如下:

package com.pkslow.ssl.config.containerfactory;

import org.apache.catalina.Context;

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.context.annotation.Bean;

import org.apache.catalina.connector.Connector;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;

@Configuration

public class HttpToHttpsContainerFactoryConfig {

@Value("${server.port}")
private int httpsPort;

@Value("${http.port}")
private int httpPort;

@Bean
public TomcatServletWebServerFactory 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);
                }
            };
    tomcat.addAdditionalTomcatConnectors(createHttpConnector());
    return tomcat;
}

private Connector createHttpConnector() {
    Connector connector =
            new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setSecure(false);
    connector.setPort(httpPort);
    connector.setRedirectPort(httpsPort);
    return connector;
}           

createHttpConnector():這個方法主要是實作了在有https前提下,打開http的功能,并配置重定向的https的端口。

3.2 配置Spring security實作重定向

有兩個配置類,一個為打開http服務,一個為實作重定向。

EnableHttpWithHttpsConfig主要作用是在已經有https的前提下,還要打開http服務。

package com.pkslow.ssl.config.security;

import org.springframework.boot.web.server.WebServerFactoryCustomizer;

import org.springframework.stereotype.Component;

public class EnableHttpWithHttpsConfig {

@Value("${http.port}")
private int httpPort;

@Component
public class CustomContainer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setPort(httpPort);
        connector.setScheme("http");
        connector.setSecure(false);
        factory.addAdditionalTomcatConnectors(connector);
    }
}           

HttpToHttpsWebSecurityConfig主要是針對Spring Security的配置,衆所周知,Spring Security是功能十分強大,但又很複雜的。代碼中已經寫了關鍵的注釋:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class HttpToHttpsWebSecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${server.port}")
private int httpsPort;

@Value("${http.port}")
private int httpPort;

@Override
protected void configure(HttpSecurity http) throws Exception {
    //redirect to https - 用spring security實作
    http.portMapper().http(httpPort).mapsTo(httpsPort);
    http.requiresChannel(
            channel -> channel.anyRequest().requiresSecure()
    );

    //通路路徑/hello不用登陸獲得權限
    http.authorizeRequests()
            .antMatchers("/hello").permitAll()
            .anyRequest().authenticated().and();
}

@Override
public void configure(WebSecurity web) throws Exception {
    //過濾了actuator後,不會重定向,也不用權限校驗,這個功能非常有用
    web.ignoring()
            .antMatchers("/actuator")
            .antMatchers("/actuator/**");
}           

4 總結

最後實作了重定向,結果展示:

本文詳細代碼可在南瓜慢說公衆号回複擷取。

參考連結:

Spring Security: 

https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-http-redirect

Springboot 1.4重定向:

https://jonaspfeifer.de/redirect-http-https-spring-boot/

原文位址

https://www.cnblogs.com/larrydpk/p/12806699.html