Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
Java
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Javachevron-right

How to Connect to MongoDB With a SOCKS5 Proxy With Java

Maxime Beugnet2 min read • Published Aug 29, 2024 • Updated Aug 29, 2024
SpringMongoDBJava
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Introduction

SOCKS5 is a standardized protocol for communicating with network services through a proxy server. It offers several advantages like allowing the users to change their virtual location or hide their IP address from the online services.
SOCKS5 also offers an authentication layer that can be used to enhance security.
In our case, the network service is MongoDB. Let's see how we can connect to MongoDB through a SOCKS5 proxy with Java.

SOCKS5 with vanilla Java

Authentication is optional for SOCKS5 proxies. So to be able to connect to a SOCKS5 proxy, you need:
  • proxyHost: IPv4, IPv6, or hostname of the proxy
  • proxyPort: TCP port number (default 1080)
If authentication is activated, then you'll also need a username and password. Both need to be provided, or it won't work.
  • proxyUsername: the proxy username (not null or empty)
  • proxyPassword: the proxy password (not null or empty)

Using connection string parameters

The first method to connect to MongoDB through a SOCKS5 proxy is to simply provide the above parameters directly in the MongoDB connection string.
1public MongoClient connectToMongoDBSock5WithConnectionString() {
2 String connectionString = "mongodb+srv://myDatabaseUser:myPassword@example.org/" +
3 "?proxyHost=<proxyHost>" +
4 "&proxyPort=<proxyPort>" +
5 "&proxyUsername=<proxyUsername>" +
6 "&proxyPassword=<proxyPassword>";
7 return MongoClients.create(connectionString);
8}

Using MongoClientSettings

The second method involves passing these parameters into a MongoClientSettings class, which is then used to create the connection to the MongoDB cluster.
1public MongoClient connectToMongoDBSocks5WithMongoClientSettings() {
2 String URI = "mongodb+srv://myDatabaseUser:myPassword@example.org/";
3 ConnectionString connectionString = new ConnectionString(URI);
4 Block<SocketSettings.Builder> socketSettings = builder -> builder.applyToProxySettings(
5 proxyBuilder -> proxyBuilder.host("<proxyHost>")
6 .port(1080)
7 .username("<proxyUsername>")
8 .password("<proxyPassword>"));
9 MongoClientSettings settings = MongoClientSettings.builder()
10 .applyConnectionString(connectionString)
11 .applyToSocketSettings(socketSettings)
12 .build();
13 return MongoClients.create(settings);
14}

Connection with Spring Boot

Using connection string parameters

If you are using Spring Boot or Spring Data MongoDB, you can connect like so if you are passing the SOCKS5 parameters in the connection string.
Most of the time, if you are using Spring Boot or Spring Data, you'll need the codec registry to support the POJO mappings. So I included this as well.
1package com.mongodb.starter;
2
3import com.mongodb.ConnectionString;
4import com.mongodb.MongoClientSettings;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import org.bson.codecs.configuration.CodecRegistry;
8import org.bson.codecs.pojo.PojoCodecProvider;
9import org.springframework.beans.factory.annotation.Value;
10import org.springframework.context.annotation.Bean;
11import org.springframework.context.annotation.Configuration;
12
13import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
14import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
15
16@Configuration
17public class MongoDBConfiguration {
18
19 @Value("${spring.data.mongodb.uri}")
20 private String connectionString;
21
22 @Bean
23 public MongoClient mongoClient() {
24 CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
25 CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
26 return MongoClients.create(MongoClientSettings.builder()
27 .applyConnectionString(new ConnectionString(connectionString))
28 .codecRegistry(codecRegistry)
29 .build());
30 }
31
32}
In this case, all the SOCKS5 action is actually happening in the application.properties file of your Spring Boot project.
1spring.data.mongodb.uri=${MONGODB_URI:"mongodb+srv://myDatabaseUser:myPassword@example.org/?proxyHost=<proxyHost>&proxyPort=<proxyPort>&proxyUsername=<proxyUsername>&proxyPassword=<proxyPassword>"}

Using MongoClientSettings

If you prefer to use the MongoClientSettings, then you can just pass a classic MongoDB URI and handle the different SOCKS5 parameters directly in the SocketSettings.Builder.
1package com.mongodb.starter;
2
3import com.mongodb.Block;
4import com.mongodb.ConnectionString;
5import com.mongodb.MongoClientSettings;
6import com.mongodb.client.MongoClient;
7import com.mongodb.client.MongoClients;
8import com.mongodb.connection.SocketSettings;
9import org.bson.codecs.configuration.CodecRegistry;
10import org.bson.codecs.pojo.PojoCodecProvider;
11import org.springframework.beans.factory.annotation.Value;
12import org.springframework.context.annotation.Bean;
13import org.springframework.context.annotation.Configuration;
14
15import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
16import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
17
18@Configuration
19public class MongoDBConfigurationSocks5 {
20
21 @Value("${spring.data.mongodb.uri}")
22 private String connectionString;
23
24 @Bean
25 public MongoClient mongoClient() {
26 CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
27 CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
28 Block<SocketSettings.Builder> socketSettings = builder -> builder.applyToProxySettings(
29 proxyBuilder -> proxyBuilder.host("<proxyHost>")
30 .port(1080)
31 .username("<proxyUsername>")
32 .password("<proxyPassword>"));
33 return MongoClients.create(MongoClientSettings.builder()
34 .applyConnectionString(new ConnectionString(connectionString))
35 .applyToSocketSettings(socketSettings)
36 .codecRegistry(codecRegistry)
37 .build());
38 }
39
40}

Conclusion

Leveraging a SOCKS5 proxy for connecting to MongoDB in Java offers enhanced security and flexibility. Whether through connection string parameters or MongoClientSettings, integrating SOCKS5 functionality is straightforward.
If you want to read more details, you can check out the SOCKS5 documentation online.
If you have questions, please head to our Developer Community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.
Top Comments in Forums
There are no comments on this article yet.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Seamless Media Storage: Integrating Azure Blob Storage and MongoDB With Spring Boot


Nov 05, 2024 | 9 min read
Quickstart

Java - MongoDB Multi-Document ACID Transactions


Mar 01, 2024 | 10 min read
Tutorial

Integrating MongoDB With Amazon Managed Streaming for Apache Kafka (MSK)


Sep 17, 2024 | 7 min read
Tutorial

Kafka to MongoDB Atlas End to End Tutorial


Jun 07, 2023 | 6 min read
Table of Contents
  • Introduction