File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
source/includes/connection-snippets/x509-snippets Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // begin x509 connection
2
+ using MongoDB . Bson ;
3
+ using MongoDB . Driver ;
4
+ using System ;
5
+ using System . IO ;
6
+ using System . Threading . Tasks ;
7
+ using System . Collections . Generic ;
8
+ using System . Security . Cryptography . X509Certificates ;
9
+
10
+ // Tested using MongoDB.Driver 2.9.2 and netcoreapp 2.2
11
+
12
+ namespace WorkingWithMongoDB
13
+ {
14
+ class Program
15
+ {
16
+ static void Main ( string [ ] args )
17
+ {
18
+ MainAsync ( ) . Wait ( ) ;
19
+ }
20
+
21
+ static async Task MainAsync ( )
22
+ {
23
+ var connectionString = "mongodb+srv://<cluster-url>/test?authSource=$external&retryWrites=true&w=majority&authMechanism=MONGODB-X509" ;
24
+ var settings = MongoClientSettings . FromConnectionString ( connectionString ) ;
25
+
26
+ // You will need to convert your Atlas-provided PEM containing the cert/private keys into a PFX
27
+ // use openssl and the following line to create a PFX from your PEM:
28
+ // openssl pkcs12 -export -in <x509>.pem -inkey <x509>.pem -out <x509>.pfx -certfile <x509>.pem
29
+ // and provide a password, which should match the second argument you pass to X509Certificate2
30
+ var cert = new X509Certificate2 ( "/etc/certs/mongodb/client-certificate.pfx" , "<pfx_passphrase>" ) ;
31
+
32
+ settings . SslSettings = new SslSettings
33
+ {
34
+ ClientCertificates = new List < X509Certificate > ( )
35
+ {
36
+ cert
37
+ }
38
+ } ;
39
+
40
+ var client = new MongoClient ( settings ) ;
41
+
42
+ // just doing a quick read to verify the usability of this connection
43
+ var database = client . GetDatabase ( "testDB" ) ;
44
+ var collection = database . GetCollection < BsonDocument > ( "testCol" ) ;
45
+
46
+ var docCount = collection . CountDocuments ( "{}" ) ;
47
+ Console . WriteLine ( docCount ) ;
48
+ }
49
+ }
50
+ }
51
+ // end x509 connection
You can’t perform that action at this time.
0 commit comments