Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readSQL
#MySQL#JDBC#Java#Security
A database vault with an rsa keyhole and a key held back by an amber bar beside a cyan tunnel

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:

  1. 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.
  2. Allow public key retrieval. allowPublicKeyRetrieval=true fetches 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.
  3. Change the authentication plugin. Setting the user to mysql_native_password works 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.

bash
# 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
properties
# 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 allowed

Reproduce it directly, without an application framework, so the message is unambiguous:

java
try (var c = DriverManager.getConnection( "jdbc:mysql://localhost:3306/app?useSSL=false", "app", "secret")) { System.out.println("connected"); } // SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Key Comparison Table

OptionProtects the passwordWorks on untrusted networkLongevity
TLS with VERIFY_IDENTITYyes, end to endyesrecommended
TLS without verificationagainst passive sniffing onlynoweak, avoid
allowPublicKeyRetrieval=true, no TLSagainst sniffing, not MITMnodev and local only
serverRSAPublicKeyFileyes, if the file is trustedyesgood for pinned keys
mysql_native_passwordSHA-1 based, weaknoremoved in MySQL 9
unix socketno password over the wirelocally onlyLinux only
SettingDefaultEffect
allowPublicKeyRetrievalfalserefuses the RSA key exchange
sslModePREFERREDtries TLS, falls back to plain
sslMode=REQUIREDnot defaultfails instead of falling back
serverRSAPublicKeyFileunsetuses a pinned key file
useSSLlegacy aliassuperseded 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:

properties
# application-default.properties - safe defaults for everything spring.datasource.url=jdbc:mysql://${DB_HOST:localhost}:3306/app?sslMode=PREFERRED
properties
# application-local.properties - explicitly local only spring.datasource.url=jdbc:mysql://localhost:3306/app?sslMode=DISABLED&allowPublicKeyRetrieval=true

Then 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:

bash
keytool -importcert -alias mysql-ca -file ca.pem \ -keystore db-truststore.jks -storepass changeit -noprompt
properties
spring.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:

sql
show status like 'Caching_sha2_password_rsa_public_key';
properties
spring.datasource.url=jdbc:mysql://db.internal:3306/app?sslMode=DISABLED&serverRSAPublicKeyFile=/etc/app/mysql-public.pem

Rotate 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:

java
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 jdbcUrl or via spring.datasource.url only, not both.
  • useSSL=true without sslMode. The legacy alias maps to PREFERRED, 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_password users must be migrated.
  • Proxies that terminate TLS and re-encrypt. VERIFY_IDENTITY fails at the database because the hostname in the certificate is the proxy's; use the proxy's CA and hostname rather than weakening to REQUIRED.

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 documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.