Skip to content

Commit 38308ab

Browse files
committed
add tls conn example
1 parent 117bd57 commit 38308ab

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

mongod.conf

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# TLS/SSL Configuration
2+
net:
3+
tls:
4+
mode: requireTLS
5+
certificateKeyFile: /certs/mongodb.pem
6+
CAFile: /certs/ca.pem

pkg/tlsconn/main.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"crypto/tls"
6+
"crypto/x509"
7+
"fmt"
8+
"os"
9+
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
)
13+
14+
func main() {
15+
16+
caFile := "certs/ca.pem"
17+
certFile := "certs/mongodb.crt" // public client certificate
18+
keyFile := "certs/mongodb.pem" // private client key
19+
passPhrase := "123" // private client key passphrase
20+
21+
// Loads CA certificate file
22+
caCert, err := os.ReadFile(caFile)
23+
if err != nil {
24+
panic(err)
25+
}
26+
caCertPool := x509.NewCertPool()
27+
if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
28+
panic("Error: CA file must be in PEM format")
29+
}
30+
// Loads client certificate files
31+
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
32+
33+
if err != nil {
34+
panic(err)
35+
}
36+
// Instantiates a Config instance
37+
tlsConfig := &tls.Config{
38+
RootCAs: caCertPool,
39+
Certificates: []tls.Certificate{cert},
40+
}
41+
uri := "mongodb://localhost:27017/?tls=true&tlsAllowInvalidCertificates=true&sslClientCertificateKeyPassword=" + passPhrase
42+
// Sets TLS options in options instance
43+
opts := options.Client().ApplyURI(uri).SetTLSConfig(tlsConfig)
44+
45+
ctx := context.TODO()
46+
client, err := mongo.Connect(ctx, opts)
47+
48+
if err != nil {
49+
panic(err)
50+
}
51+
defer client.Disconnect(ctx)
52+
53+
err = client.Ping(ctx, nil)
54+
if err != nil {
55+
panic(err)
56+
}
57+
58+
fmt.Println("Connected to MongoDB!")
59+
}

0 commit comments

Comments
 (0)