添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Microsoft – NPI EA (cat=Spring)
announcement - icon

Connect with experts from the Java community, Microsoft, and partners to “Code the Future with AI” JDConf 2025, on April 9 -

Dedicated local streams across North America, Europe, and Asia-Pacific will explore the latest Java AI models to develop LLM apps and agents, learning best practices for app modernization with AI-assisted dev tools, learning the latest in Java frameworks, security, and quite a bit more:

>> Register today

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide :

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls . A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Download the E-book

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

Download the Guide

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Overview

An unencrypted connection between a MySQL server and a client can expose data in transit over the network. For a production-ready application, we should move all communication to a secure connection via TLS (Transport Layer Security) protocol.

In this tutorial, we’ll learn how to enable a secure connection on a MySQL server. Also, we’ll configure the Spring Boot application to use this secure connection.

2. Why Use TLS on MySQL?

First, let’s understand some basics of TLS.

The TLS protocol uses an encryption algorithm to ensure that data received over the network can be trusted and not tampered with or inspected. It has mechanisms to detect data change, loss, or replay attacks. TLS also incorporates algorithms that provide identity verification using the X.509 standard.

An encrypted connection adds a layer of security and makes the data unreadable over the network traffic.

Configuring a secure connection between the MySQL server and client enables better authentication, data integrity, and trustworthiness. Additionally, the MySQL server can perform additional checks on the client’s identity.

However, such a secure connection comes with a performance penalty due to encryption. The severity of the performance cost depends on various factors like query size, data load, server hardware, network bandwidth, and other factors.

3. Configure a TLS Connection on MySQL Server

MySQL server performs encryption on a per-connection basis, and this can be made mandatory or optional for the given user. MySQL supports SSL encryption-related operations at runtime with the installed OpenSSL library.

We can use the JDBC Driver Connector/J to encrypt the data between the client and server after the initial handshake.

MySQL server v8.0.28 or above supports only TLS v1.2 and TLS v1.3. It no longer supports the earlier versions of TLS (v1 and v1.1).

Server authentication can be enabled using either a certificate signed by a trusted root certificate authority or a self-signed certificate . Also, it’s common practice to build our own root CA file for MySQL , even in production.

Additionally, the server can authenticate and verify the client’s SSL certificate and perform additional checks on the client’s identity.

3.1. Configure MySQL Server With TLS Certificates

We’ll enable secure transport on the MySQL server using the property require_secure_transport and the default-generated certificates .

Let’s quickly bootstrap the MySQL Server by implementing the settings in a docker-compose.yml :

version: '3.8'
services:
  mysql-service:
    image: "mysql/mysql-server:8.0.30"
    container_name: mysql-db
    command: [ "mysqld",
      "--require_secure_transport=ON",
      "--default_authentication_plugin=mysql_native_password",
      "--general_log=ON" ]
    ports:
      - "3306:3306"
    volumes:
      - type: bind
        source: ./data
        target: /var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_HOST: "%"
      MYSQL_ROOT_PASSWORD: "Password2022"
      MYSQL_DATABASE: test_db

We should note that the above MySQL Server uses the default certificates located in path /var/lib/mysql .

Alternatively, we can override the default certificates by including a few mysqld configs in docker-compose.yml :

command: [ "mysqld",
  "--require_secure_transport=ON",
  "--ssl-ca=/etc/certs/ca.pem",
  "--ssl-cert=/etc/certs/server-cert.pem",
  "--ssl-key=/etc/certs/server-key.pem",
  ....]

Now, let’s start the mysql-service using the docker-compose command:

$ docker-compose -p mysql-server up

3.2. Create a User with X509

Optionally, we can configure the MySQL server with client identification using the X.509 standard. With X509 , a valid client certificate is required. This enables the two-way mutual TLS or mTLS .

Let’s create a user with X509 and grant permission on the test_db database:

mysql> CREATE USER 'test_user'@'%' IDENTIFIED BY 'Password2022' require X509;
mysql> GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'%';

We can set up a TLS connection without any user certificate identification:

mysql> CREATE USER 'test_user'@'%' IDENTIFIED BY 'Password2022' require SSL;

We should note that the client is required to provide a truststore if SSL is used.

4. Configure TLS on a Spring Boot Application

Spring Boot applications can configure TLS over the JDBC connection by setting the JDBC URL with a few properties.

There are various ways of configuring Spring Boot Application to use TLS with MySQL.

Before that, we’ll need to convert the truststore and client certificates into JKS format.

4.1. Convert PEM File to JKS Format

Let’s convert the MySQL server-generated ca.pem and client-cert.pem files to JKS format:

keytool -importcert -alias MySQLCACert.jks -file ./data/ca.pem \
    -keystore ./certs/truststore.jks -storepass mypassword
openssl pkcs12 -export -in ./data/client-cert.pem -inkey ./data/client-key.pem \
    -out ./certs/certificate.p12 -name "certificate"
keytool -importkeystore -srckeystore ./certs/certificate.p12 -srcstoretype pkcs12 -destkeystore ./certs/client-cert.jks

We should note that, as of Java 9, the default keystore format is PKCS12.

4.2. Configure Using application.yml

TLS can be enabled with the sslMode set as PREFERRED, REQUIRED, VERIFY_CA, or VERIFY_IDENTITY.

The PREFERRED mode either uses the secure connection, if the server supports it, or otherwise falls back to an unencrypted connection.

With REQUIRED mode, the client can only use an encrypted connection. Like REQUIRED, VERIFY_CA mode uses a secure connection but additionally validates the server certificates against the configured Certificate Authority (CA) certificates.

The VERIFY_IDENTITY mode does one additional check on the hostname along with certificate validation.

Also, a few Connector/J properties need to be added to the JDBC URL, such as trustCertufucateKeyStoreUrl, trustCertificateKeyStorePassword, clientCertificateKeyStoreUrl, and clientCertificateKeyStorePassword.

Let’s configure the JDBC URL in the application.yml with sslMode set to VERIFY_CA:

spring:
  profiles: "dev2"
  datasource:
    url: >-
         jdbc:mysql://localhost:3306/test_db?
         sslMode=VERIFY_CA&
         trustCertificateKeyStoreUrl=file:/<project-path>/mysql-server/certs/truststore.jks&
         trustCertificateKeyStorePassword=mypassword&
         clientCertificateKeyStoreUrl=file:/<project-path>/mysql-server/certs/client-cert.jks&
         clientCertificateKeyStorePassword=mypassword
    username: test_user
    password: Password2022

We should note that the deprecated properties equivalent to VERIFY_CA are a combination of useSSL=true and verifyServerCertificate=true.

If the trust certificate files are not provided, we’ll get an error to that effect:

Caused by: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
	at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:157) ~[na:na]
	at java.base/sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:83) ~[na:na]
	at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309) ~[na:na]
	at com.mysql.cj.protocol.ExportControlled$X509TrustManagerWrapper.checkServerTrusted(ExportControlled.java:402) ~[mysql-connector-java-8.0.29.jar:8.0.29]

In case the client certificate is missing, we’ll get a different error:

Caused by: java.sql.SQLException: Access denied for user 'test_user'@'172.20.0.1'

4.3. Configure TLS Using Environment Variables

Alternatively, we can set the above configuration as environment variables and include the SSL-related configs as JVM parameters.

Let’s add the TLS and Spring-related configs as environment variables:

export TRUSTSTORE=./mysql-server/certs/truststore.jks
export TRUSTSTORE_PASSWORD=mypassword
export KEYSTORE=./mysql-server/certs/client-cert.jks
export KEYSTORE_PASSWORD=mypassword
export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/test_db?sslMode=VERIFY_CA
export SPRING_DATASOURCE_USERNAME=test_user
export SPRING_DATASOURCE_PASSWORD=Password2022

Then, let’s run the application with the above SSL configurations:

$java -Djavax.net.ssl.keyStore=$KEYSTORE \
 -Djavax.net.ssl.keyStorePassword=$KEYSTORE_PASSWORD \
 -Djavax.net.ssl.trustStore=$TRUSTSTORE \
 -Djavax.net.ssl.trustStorePassword=$TRUSTSTORE_PASSWORD \
 -jar ./target/spring-boot-mysql-0.1.0.jar

5. Verify the TLS Connection

Let’s now run the application using any of the above methods and verify the TLS connection.

The TLS connection can be verified using the MySQL server general log or by querying the process and sys admin tables.

Let’s verify the connections using the log file in its default path /var/lib/mysql/:

$ cat /var/lib/mysql/7f44397082d7.log
2022-09-17T13:58:25.887830Z        19 Connect   [email protected] on test_db using SSL/TLS

Alternatively, let’s verify the connections used by test_user:

mysql> SELECT process.thd_id,user,db,ssl_version,ssl_cipher FROM sys.processlist process, sys.session_ssl_status session 
where process.user='[email protected]'and process.thd_id=session.thread_id;+--------+----------------------+---------+-------------+------------------------+
| thd_id | user                 | db      | ssl_version | ssl_cipher             |
+--------+----------------------+---------+-------------+------------------------+
|    167 | [email protected] | test_db | TLSv1.3     | TLS_AES_256_GCM_SHA384 |
|    168 | [email protected] | test_db | TLSv1.3     | TLS_AES_256_GCM_SHA384 |
|    169 | [email protected] | test_db | TLSv1.3     | TLS_AES_256_GCM_SHA384 |

6. Conclusion

In this article, we’ve learned how a TLS connection to MySQL makes the data secure over the network. Also, we’ve seen how to configure the TLS connection on MySQL Server in a Spring Boot Application.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Microsoft – NPI EA (cat= Spring)
announcement - icon

Connect with experts from the Java community, Microsoft, and partners to “Code the Future with AI” JDConf 2025, on April 9 -

Dedicated local streams across North America, Europe, and Asia-Pacific will explore the latest Java AI models to develop LLM apps and agents, learning best practices for app modernization with AI-assisted dev tools, learning the latest in Java frameworks, security, and quite a bit more:

>> Register today

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>>Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Microsoft – NPI (cat=Spring)
announcement - icon

Connect with experts from the Java community, Microsoft, and partners to “Code the Future with AI” JDConf 2025, on April 9 -

Dedicated local streams across North America, Europe, and Asia-Pacific will explore the latest Java AI models to develop LLM apps and agents, learning best practices for app modernization with AI-assisted dev tools, learning the latest in Java frameworks, security, and quite a bit more:

Register today

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
Course – All Access – NPI EA (cat= Spring)
All Access Course Banner
Course – LSSO – NPI EA (tag = OAuth)
LSSO Course Banner
Course – LSD – NPI EA (tag=Spring Data JPA)
eBook – Guide Junit – NPI EA (tag=JUnit)
Course – RWSB – NPI EA (cat=REST)
RWSB Course Banner
eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
eBook – Jackson – NPI EA – 2 (cat=Jackson)
Download the E-book
eBook – RwS Java – NPI EA (cat=Java)
Download the E-book
eBook – Maven – NPI EA (cat= Maven)
Download the E-book
eBook- Spring Reactive Guide – NPI EA (cat=Reactive)
Download the E-book
eBook – Mockito – NPI EA (tag=Mockito)
Download the Guide
eBook – Persistence – NPI EA (cat=Persistence)
Course – LSS – NPI (cat=Security)
LSS Course Banner