SpringbootはTomcatをコンテナとして使用して、httpをhttpsにリダイレクトする2つの方法を実現します。

1はじめに

この記事では、Springbootのコードを介してHttpからHttpsへのリダイレクトを実装する方法を紹介します。この記事では、Tomcatをコンテナーとして使用する場合についてのみ説明します。他のコンテナーは将来まとめられます。

ここに写真の説明を挿入

2.関連する概念

2.1リダイレクトとは

いわゆるリダイレクションとは、元々アドレスAを閲覧したかったのですが、サーバーに到着した後、サーバーはアドレスAのインターフェースがもう存在しないか、アクセスする権限がないと判断します。アドレスAにアクセスする必要はありません。別のアドレスBを教えてください。次に、アドレスBにアクセスします。

通常、リダイレクトには2つのリターンコードがあります。

  • 301:永続的なリダイレクト。
  • 302:一時的なリダイレクト。

Chromeを介してネットワークの詳細を確認し、いくつかのWebサイトのリダイレクトを記録します。

ウェブサイト ドメイン名 リダイレクトコード リダイレクト後のURL
カボチャについてゆっくり話す www.pkslow.com 301 https://www.pkslow.com
グーグル www.google.com 307 https://www.google.com
林檎 www.apple.com 307 https://www.apple.com
Alipay www.alipay.com 301 https://www.alipay.com
QQ www.qq.com 302 https://www.qq.com
Baidu www.baidu.com 307 https://www.baidu.com

注:307も一種のリダイレクトであり、新しいステータスコードです。

2.2リダイレクトする理由

上に具体的にリストした表と組み合わせて、なぜこの種のリダイレクトが必要なのか考えますか?上記のリダイレクトが1つのことを行っていることを見つけるのは難しくありません。それはhttpをhttpsにリダイレクトすることです。その理由は次のとおりです。

(1)httpは安全ではないため、安全なhttpsURLを使用する必要があります。

(2)ただし、ユーザーがWebサイトにアクセスするたびにhttps://を入力するように要求することはできません。これは面倒なので、wwwであっても、誰もがドメイン名のみを入力することに慣れています。したがって、ユーザーの入力は実際にはhttp Webページにアクセスすることであり、安全なアクセスの要件を満たすには、httpsにリダイレクトする必要があります。

2.3リダイレクトする方法

まず、サーバーはhttpとhttpsの両方を同時にサポートする必要があります。そうしないと、リダイレクトが行われません。サポートを提供するにはhttpsが必要なので、なぜhttpサービスを提供するのでしょうか。httpsに直接アクセスする必要はありませんか?その理由は前述したとおりです。誰もが簡単なドメイン名を入力するだけでアクセスできます。現時点ではhttpです。httpサポートを提供しない場合、ユーザーはWebサイトがすでにダウンしていると考えます。

どちらのプロトコルもサポートを提供するため、2つのソケットポートを開く必要があります。通常、httpは80、httpsは443です。次に、すべてのHTTPリクエストをhttpsにリダイレクトする必要があります。サーバーが異なれば実装も異なります。ここで、Springboot + Tomcatの実装を紹介します。

3. SpringbootTomcatはリダイレクトを実装します

SpringbootがTomcatをサーブレットコンテナとして使用する場合、リダイレクトを実現する方法は2つあります。1つはSpring Securityを使用しない方法、もう1つはSpringSecurityを使用する方法です。コード構造は次のとおりです。
ここに写真の説明を挿入
メインクラスコードは次のとおりです。

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"):@ 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

2つのポートを指定する必要があります。server.portはhttpsポート、http.portはhttpポートです。httpsがない場合、server.portはhttpポートを参照することに注意してください。

3.1リダイレクトを実装するようにContainerFactoryを構成する

構成されたクラスは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セキュリティを構成する

2つの構成クラスがあります。1つはhttpサービスを開くためのもので、もう1つはリダイレクトを実装するためのものです。

EnableHttpWithHttpsConfigの主な機能は、httpsがあることを前提としてhttpサービスを開くことです。

package com.pkslow.ssl.config.security;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
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は非常に強力ですが、非常に複雑です。重要なコメントはコードに書かれています:

package com.pkslow.ssl.config.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
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/**");
    }
}

結論:

資料を学ぶ必要がある友達は、クリックして入力できます。パスワード:cspp、無料で入手できます
ここに写真の説明を挿入

ここに写真の説明を挿入

おすすめ

転載: blog.csdn.net/m0_45270667/article/details/109220901