MySQL 8: Public Key Retrieval is not allowed over JDBC
The driver never sent the password. Use verified TLS, or allow key retrieval only where the network is trusted.

Introduction & Quick Summary
A JDBC connection to MySQL 8 fails at login with:
java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
Nothing is wrong with the password: the driver never sent it. MySQL 8's default authentication plugin, caching_sha2_password, needs the server's RSA public key to encrypt the password when the connection is not already protected by TLS. The Connector/J property allowPublicKeyRetrieval defaults to false, so the driver refuses to fetch that key and aborts the handshake.
Three ways forward, and they are not equivalent:
- Enable TLS. With a verified TLS connection the password is protected by the channel and no key retrieval is needed. This is the correct production fix.
- Allow public key retrieval.
allowPublicKeyRetrieval=truefetches the key over the connection. It is fine on localhost or a trusted private network and unsafe on an untrusted one, because an attacker in the middle can supply their own key. - Change the authentication plugin. Setting the user to
mysql_native_passwordworks and is a dead end: that plugin is deprecated and removed in MySQL 9.
The second option is what most tutorials show because it is one URL parameter. Use it deliberately, and know what it costs.
Core Mechanics, Signatures & Reproducible Setup
caching_sha2_password authenticates with a SHA-256 hash. On a fresh connection without TLS, the client must send the password RSA-encrypted with the server's public key. The server publishes that key, but a client that trusts any key it is handed can be tricked into revealing the password, which is exactly why Connector/J requires an explicit opt-in.
# which plugin does the account use
mysql -u root -p -e "select user, host, plugin from mysql.user where user='app';"
# app % caching_sha2_password# the two URL shapes, spelled out
spring.datasource.url=jdbc:mysql://localhost:3306/app?allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.url=jdbc:mysql://db.internal:3306/app?sslMode=VERIFY_IDENTITY&trustCertificateKeyStoreUrl=file:/certs/db.jks# docker compose, the configuration that produces the error most often
services:
db:
image: mysql:8.4
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: app
MYSQL_PASSWORD: secret
MYSQL_DATABASE: app
api:
build: .
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/app?useSSL=false
# login fails here with Public Key Retrieval is not allowedReproduce it directly, without an application framework, so the message is unambiguous:
try (var c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/app?useSSL=false", "app", "secret")) {
System.out.println("connected");
}
// SQLNonTransientConnectionException: Public Key Retrieval is not allowedKey Comparison Table
| Option | Protects the password | Works on untrusted network | Longevity |
|---|---|---|---|
| TLS with VERIFY_IDENTITY | yes, end to end | yes | recommended |
| TLS without verification | against passive sniffing only | no | weak, avoid |
| allowPublicKeyRetrieval=true, no TLS | against sniffing, not MITM | no | dev and local only |
| serverRSAPublicKeyFile | yes, if the file is trusted | yes | good for pinned keys |
| mysql_native_password | SHA-1 based, weak | no | removed in MySQL 9 |
| unix socket | no password over the wire | locally only | Linux only |
| Setting | Default | Effect |
|---|---|---|
| allowPublicKeyRetrieval | false | refuses the RSA key exchange |
| sslMode | PREFERRED | tries TLS, falls back to plain |
| sslMode=REQUIRED | not default | fails instead of falling back |
| serverRSAPublicKeyFile | unset | uses a pinned key file |
| useSSL | legacy alias | superseded by sslMode |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The local development fix, written down as local
Keep the permissive flag out of the shared configuration so it cannot reach production by accident:
# application-default.properties - safe defaults for everything
spring.datasource.url=jdbc:mysql://${DB_HOST:localhost}:3306/app?sslMode=PREFERRED# application-local.properties - explicitly local only
spring.datasource.url=jdbc:mysql://localhost:3306/app?sslMode=DISABLED&allowPublicKeyRetrieval=trueThen run with --spring.profiles.active=local. A single application.properties with the flag in it is how a production deployment ends up allowing key retrieval because someone copy-pasted a tutorial.
2. Docker Compose and Spring Boot defaults
A MySQL 8 or 8.4 container with a fresh user creates that user with caching_sha2_password. A Spring Boot app connecting without TLS hits the error on first login, and the stack trace points at Hikari's pool start rather than at the URL, which sends people looking in the wrong place:
services:
api:
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/app?sslMode=DISABLED&allowPublicKeyRetrieval=true
depends_on:
db: { condition: service_healthy }On a compose network the traffic does not leave the host, so the flag costs little; the same flag in a cloud deployment crosses a network you do not control.
3. Doing it properly with TLS
A verified TLS connection removes the need for the RSA exchange entirely. Generate a server certificate, put its CA in a truststore, and point the driver at it:
keytool -importcert -alias mysql-ca -file ca.pem \
-keystore db-truststore.jks -storepass changeit -nopromptspring.datasource.url=jdbc:mysql://db.internal:3306/app?sslMode=VERIFY_IDENTITY
spring.datasource.hikari.data-source-properties.trustCertificateKeyStoreUrl=file:/certs/db-truststore.jks
spring.datasource.hikari.data-source-properties.trustCertificateKeyStorePassword=${TRUSTSTORE_PASS}VERIFY_IDENTITY checks the hostname as well as the chain. REQUIRED encrypts without verifying, which is better than plain but does not stop an active attacker.
4. Pinning the public key instead of allowing retrieval
When TLS is not practical but the network is only partly trusted, ship the server's public key with the application and point the driver at it. The key cannot be swapped by a middlebox:
show status like 'Caching_sha2_password_rsa_public_key';spring.datasource.url=jdbc:mysql://db.internal:3306/app?sslMode=DISABLED&serverRSAPublicKeyFile=/etc/app/mysql-public.pemRotate the file when the server's key changes, and mount it read-only. A stale key produces IllegalArgumentException: Could not read the public key rather than the original error.
5. Changing the plugin is a temporary answer
ALTER USER app@'%' IDENTIFIED WITH mysql_native_password BY 'secret'; clears the error immediately and is still wrong as a plan: mysql_native_password is deprecated in MySQL 8.0.34 and removed in 9.0, and the hash it stores is weaker. If a managed service offers it, treat it as a compatibility bridge while TLS is arranged:
select user, host, plugin from mysql.user;
alter user 'app'@'%' identified with caching_sha2_password by 'secret';Note that the plugin change alone does not fix TLS: a caching_sha2_password account still needs either TLS or key retrieval.
6. Checking the URL you actually built
Connection strings assembled from environment variables hide mistakes well. Print the resolved URL with the password removed, and parse it rather than eyeballing a long line:
var url = dataSource.getConnection().getMetaData().getURL();
System.out.println(url.replaceAll("password=[^&]*", "password=***"));sslMode=DISABLED and allowPublicKeyRetrieval=true are both visible in the parameter list once it is printed. When a URL is built by string concatenation, percent-encode values first and inspect the parameters in URL Encoder / Decoder: an unencoded & in a password silently truncates everything after it, including these two flags.
Common Compilation/Runtime Mistakes & Version Gotchas
- Adding the flag to the JDBC URL for a connection pool that builds its own. Hikari can override the URL; set it on the pool's
jdbcUrlor viaspring.datasource.urlonly, not both. useSSL=truewithoutsslMode. The legacy alias maps toPREFERRED, which falls back to plain text and leaves the RSA exchange in play.- Copying the flag into a production secret. The one line that makes local development work becomes the one line that allows a MITM to capture the database password.
- Connector/J version differences. 8.x enforces the property; older 5.x drivers against an 8.x server fail with the same text but do not support
sslMode. Match the driver to the server, and prefer a recent 9.x connector. - A truststore with the wrong alias or a missing hostname. TLS then fails with
SSLHandshakeException, which looks unrelated to the original error but has the same root cause: no channel to protect the password. - MySQL 9 environments. Changing the plugin is no longer available, so either TLS or key retrieval is required, and
mysql_native_passwordusers must be migrated. - Proxies that terminate TLS and re-encrypt.
VERIFY_IDENTITYfails at the database because the hostname in the certificate is the proxy's; use the proxy's CA and hostname rather than weakening toREQUIRED.
Primary references: Connector/J's security connection properties documents allowPublicKeyRetrieval, serverRSAPublicKeyFile and sslMode with their defaults, and MySQL's Caching SHA-2 Pluggable Authentication explains why the RSA key exchange exists at all.
Official references
primary documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
MySQL: ERROR 1040 (HY000) Too many connections
The server is out of slots because pools are too large or leaking. Read the counters, size pools against replicas, then raise the limit.
Postgres: invalid input syntax for type uuid
An empty filter or a legacy id reaches a uuid parameter. Treat absent as no filter and validate before the query.
MySQL: Lock wait timeout exceeded, and how to find the blocker
The waiter is the symptom. Find the blocker, shorten the transaction that holds locks, and stop raising the timeout as a fix.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.