Enable and Configure TLS
On this page
Overview
In this guide, you can learn how to use the TLS protocol to secure your connection to a MongoDB deployment. To configure your connection to use TLS, enable the TLS option and provide your certificates for validation when creating a client.
This guide includes the following sections:
Enable TLS describes ways to enable TLS on your connection
Configure Certificates describes the certificates required to configure TLS
Reference Certificates in a Client provides an example of how to create a
Config
struct to configure your TLS optionsAdditional Information provides links to resources and API documentation for types and methods mentioned in this guide
Tip
To learn more about TLS, see the Wikipedia entry on Transport Layer Security.
Enable TLS
You can enable TLS on a connection to your MongoDB instance in one of the following ways:
Setting the
tls
option totrue
in your connection stringPassing an empty
Config
struct to theSetTLSConfig()
method when creating aClientOptions
instance
Select from the following Connection String and ClientOptions tabs to see a corresponding code sample:
uri := "mongodb://<hostname>:<port>?tls=true" opts := options.Client().ApplyURI(uri) client, _ := mongo.Connect(context.TODO(), opts)
uri := "<connection string>" opts := options.Client().ApplyURI(uri).SetTLSConfig(&tls.Config{}) client, _ := mongo.Connect(context.TODO(), opts)
Note
If your connection string uses a DNS SRV record by including
the mongodb+srv
prefix, TLS is enabled on your connection by
default.
For a full list of client options, see Connection Options.
Configure Certificates
To successfully initiate a TLS request, your application must present cryptographic certificates to prove its identity. Your application's certificates must be stored as PEM files to enable TLS when connecting.
Important
For production use, we recommend that your MongoDB deployment use valid certificates generated and signed by the same certificate authority. For testing, your deployment can use self-signed certificates.
The following list describes the components that your client must present to establish a TLS-enabled connection:
TLS Component | Description |
---|---|
Certificate Authority (CA) | One or more certificate authorities to
trust when making a TLS connection. |
Client Certificate | A digital certificate that allows the server to verify the identity
of your application to establish an encrypted network connection. |
Certificate Key | The client certificate private key file. This key is often
included within the certificate file itself. |
Passphrase | The password to decrypt the private client key if it is encrypted. |
Reference Certificates in a Client
You must reference your certificates in your ClientOptions
object so that the server can validate them before the client connects.
We recommend that you set the TLSConfig
field of your
ClientOptions
instance to a Config
struct to configure your
TLS connection. Config
structs are native to Go and allow you to keep
all your TLS options in a single reusable object.
To create a Config
instance, import the crypto/tls
and
crypto/x509
packages. Next, create a Config
struct instance and
set the relevant struct fields for your configuration.
Within your Config
instance, you can set optional
fields to configure TLS on your connection. For testing purposes,
you can set the InsecureSkipVerify
field to true
.
Warning
Setting the InsecureSkipVerify
field to true
disables
both certificate and hostname validation.
Specifying this option in a production environment makes your application insecure and potentially vulnerable to expired certificates and foreign processes posing as valid client instances.
To learn more about the Config
struct, see the tls.Config API
documentation.
Example
This example performs the following actions to create a Config
instance and a Client
instance with TLS enabled:
Creates variables to reference the certificate filepaths
Creates a CA file pool by using the
x509.NewCertPool()
method and appends the contents of the CA fileLoads the client certificate files by using the
tls.LoadX509KeyPair()
methodInstantiates a
Config
struct and sets theRootCAs
andCertificates
fieldsPasses the
Config
instance to theSetTLSConfig()
method to set theTLSConfig
field of theClientOptions
// Enable TLS on a connection by using the Go driver package main import ( "context" "crypto/tls" "crypto/x509" "os" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { caFile := "<path to CA certificate>" certFile := "<path to public client certificate>" keyFile := "<path to private client key>" // Loads CA certificate file caCert, err := os.ReadFile(caFile) if err != nil { panic(err) } caCertPool := x509.NewCertPool() if ok := caCertPool.AppendCertsFromPEM(caCert); !ok { panic("Error: CA file must be in PEM format") } // Loads client certificate files cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { panic(err) } // Instantiates a Config instance tlsConfig := &tls.Config{ RootCAs: caCertPool, Certificates: []tls.Certificate{cert}, } uri := "<connection string>" // Sets TLS options in options instance opts := options.Client().ApplyURI(uri).SetTLSConfig(tlsConfig) // Connects to MongoDB with TLS enabled client, err := mongo.Connect(context.TODO(), opts) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() }
Additional Information
To learn more about enabling TLS on a connection, see the following Server manual documentation:
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation: