Home > Article > Backend Development > How to Fix \'x509: certificate relies on legacy Common Name field\' Error When Connecting to MongoDB with Go?
Error: Connecting to Server with Legacy Common Name Field
When attempting to establish a connection to a MongoDB server using Go, you may encounter the error:
failed to connect: x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0
This error indicates that the certificate used for TLS authentication contains a Common Name (CN) field but lacks the necessary Subject Alternative Name (SAN) fields. Go's TLS implementation has become stricter in recent versions, and it now favors SANs over CNs for host verification.
Root Cause:
The root cause of this error lies in the misconfiguration of the SSL certificate used for TLS authentication. The certificate should have a DNS SAN field matching the hostname or IP address of the MongoDB server.
Solution:
To resolve this error, you need to regenerate the SSL certificate with a DNS SAN field. This can be achieved using the following steps:
Create a CSR (Certificate Signing Request):
openssl req -new \ -subj "${SUBJ_PREFIX}/CN=${DNS}/emailAddress=${EMAIL}" \ -key "${KEY}" \ -addext "subjectAltName = DNS:${DNS}" \ -out "${CSR}"
Sign the CSR with Your Root CA:
openssl ca \ -create_serial \ -cert "${ROOT_CRT}" \ -keyfile "${ROOT_KEY}" \ -days "${CERT_LIFETIME}" \ -in "${CSR}" \ -batch \ -config "${CA_CONF}" \ -out "${CRT}"
Inspect the Resulting Certificate:
openssl x509 -in server.crt -noout -text
You should now have a certificate with a SAN section like:
X509v3 Subject Alternative Name: DNS:myserver.com
Once you have regenerated the certificate, you can use it to establish a secure connection to the MongoDB server without encountering the Common Name error.
The above is the detailed content of How to Fix \'x509: certificate relies on legacy Common Name field\' Error When Connecting to MongoDB with Go?. For more information, please follow other related articles on the PHP Chinese website!