SoFunction
Updated on 2025-03-03

SpringBoot's project practice integrating HTTPS

1_Https function

Protect the security of users' privacy information:

On HTTP website data is transmitted in plain text, customers' privacy is very easy to be stolen and leaked. Deploy SSL certificates and data is transmitted encrypted by HTTPS, which can protect communications from being listened to and stolen by third parties, thereby protecting user privacy and security. It can also increase user trust and enhance corporate image.

Protect the security and integrity of the website:

HTTPS is a secure socket layer hypertext transmission protocol, which can ensure that the transmission of website information from the user's browser to the server is highly encrypted and transmitted, and will not be stolen or tampered by third parties. It can also prevent the website from being hijacked and inserted into advertisements, prevent it from being attacked by phishing websites, thereby protecting the security and integrity of the website.

Prevent attacks by phishing websites and effectively identify the true identity of the website:

The http website will be marked "unsafe" by the browser, and installing the https certificate will cancel this "unsafe" warning, which can increase the trust of the visitor. At the same time, for websites with OV SSL certificates or EV SSL certificates installed, the website's true identity can be proved to the user to prevent the website from being counterfeited by phishing websites.

2_Get certificate

You need to apply for or purchase an SSL certificate from the SSL certificate authority and download the corresponding.pemand.keydocument.

Since it is only local testing, the JDK1.8 development kit under the bin directory will be used hereTool generationsslKey:

keytool -genkeypair -alias myalias -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 -storepass your-password

  • -genkeypair: Indicates the creation of a key.
  • -alias: an alias when saving.
  • -keyalg: Encryption algorithm selection, RSA is used here.
  • -keysize: The key size has fixed requirements.
  • -storetype: The type of the key repository.
  • -keystore: where the key is stored.
  • -validity: Validity time, unit is day.
  • -storepass: keystore password.

You can use code to verify whether the key generation is correct, such as:

package ;

import ;
import ;
import ;
import ;
import ;

public class KeystoreExample {
    public static void main(String[] args) {
        String keystorePath = "path/to/your/keystore.p12";
        char[] keystorePassword = "your-keystore-password".toCharArray();

        try (FileInputStream fis = new FileInputStream(keystorePath)) {
            KeyStore keystore = (());
            (fis, keystorePassword);
            ("Keystore loading successfully");
        } catch ( e) {
            ("Keystore failed to load: " + ());
        } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException e) {
            ("It may be a password error that leads to decryption failure");
            ();
        }
    }
}

Or useTools for verification:

keytool -list -v -keystore  keystore.p12

3_Configuration Items

=8081
=/log
=30s
# Set the context path of the application to /test002.  This means that all URLs starting with /test002 will be considered to belong to this application.-path=/test002
-encoding=UTF-8
=500
# Indicates the type of the key repository-store-type=PKCS12
# Indicates that the name of the SSL keystore is keystore.p12-store=classpath:ssl/keystore.p12
# Indicates that the SSL key is alias .-alias=myalias
# This line sets the password of the SSL key repository as your-password# The password cannot be very simple, otherwise an exception will occur when the project starts.-store-password=your-password

in,ConfigurationHTTPSListen to the port.-storeConfigure the certificate storage path,-store-passwordConfigure the certificate password,-store-typeand-aliasSpecify the type and alias of the certificate respectively.

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
    <modelVersion>4.0.0</modelVersion>

    <groupId></groupId>
    <artifactId>spring_Back</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId></groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.</version>
        <relativePath/>
    </parent>
    <properties>
        <>8</>
        <>8</>
        <>UTF-8</>
    </properties>
    <dependencies>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
</project>

4_Configuration Class

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
public class TomcatConfig {
    /**
      * Set up the Server configuration of Tomcat
      * @return
      */
    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory(){
        TomcatServletWebServerFactory myFactory = new TomcatServletWebServerFactory(){
            //Create a security constraint object            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                ("CONFIDENTIAL");//Set to confidential level                SecurityCollection connection = new SecurityCollection();//Set a secure connection object                //It works on all routes                ("/*");
                 //Add the connection object to the secure route
                 (connection);
                 (constraint);
             }
         };
         //Configure HTTPS connector
         (createConnector());
         return myFactory;
     }
 
     /**
      * Create a connection compatible with Https requests
      * @return
      */
    private Connector createConnector(){
        //tomcat 9        //Do not use .http11.Http11AprProtocol in tomcat/conf/        //Use HTTP/1.1        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);//"HTTP/1.1"
 
        ("http");
        (8080);
        (false);//Close SSL check        //Set the port to jump to 8081        (8081);
        return connector;
    }
}

This code creates aTomcat ServletContainer and configured with aHTTPSConnector. inredirectConnector()The method has been implementedHTTPRequest redirect toHTTPSFunctions.

  • Start the project: After completing the above configuration, restart the project and you canHTTPSAccess under the agreementWebApplied.

It should be noted that in the actual production environment, the server's firewall, load balancing and other related components need to be configured to ensure thatHTTPSSafety and stability.

5_Control Class

package ;
 
import ;
import ;
 
@RestController
public class FirstController {
    @GetMapping("/hey")
    public String hey(){
        return "hey main";
    }
}

6_Start class

package ;

import ;
import ;
import ;

@EnableAutoConfiguration
@ComponentScan
public class MyApp {
    public static void main(String[] args) {
        (,args);
    }
}

At this time, accessing port 8080 using the http protocol will jump to port 8081 under the https protocol.

This is the end of this article about the project practice of SpringBoot integrating HTTPS. For more related content related to SpringBoot integrating HTTPS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!