MongoDB Atlas Authentication Using Service Accounts (OAuth)
Wojciech Trocki9 min read • Published Jan 23, 2025 • Updated Jan 23, 2025
Rate this tutorial
MongoDB's Atlas Administration API provides a powerful way to interact with MongoDB Atlas resources. It enables you to manage your Atlas organizations, projects, deployments, and more, allowing you to seamlessly automate and integrate administrative tasks directly into your applications or CI/CD systems. MongoDB Atlas offers various API clients, including the Atlas CLI and Terraform providers. In certain scenarios, you can leverage direct programmatic access from applications and automation systems written in languages like Go, Python, or Node.js.
With the introduction of the Service Accounts for Atlas Administration API, you now can use OAuth2 token credentials when performing API requests. The OAuth2 standard simplifies authentication with the Atlas API compared to the previously used digest authentication. Service Accounts, currently available as a preview feature, offer a new way to authenticate to Atlas using the industry-standard OAuth 2.0 with the Client Credentials flow. This provides a secure and efficient method to manage access to your Atlas resources.
In this tutorial, we will guide you through the process of setting up a service account using the Atlas SDK Go, Node.js, and Python. We will provide instructions on obtaining the necessary credentials and making programmatic API requests to MongoDB Atlas directly from your application.
Service Accounts provide a new way to authenticate to Atlas using OAuth 2.0 with the Client Credentials flow. A service account provides a client ID and client secret, which are used to generate access tokens for performing API requests. Access tokens are currently valid for one hour. Service accounts are created within an Atlas organization and can be configured to access multiple projects within that organization.
Before you begin, ensure you have the following:
- A MongoDB Atlas account. If you don’t have one already, follow the Get Started With Atlas guide to create your account and first cluster.
- A service account with a client ID and client secret.
- Once you have created a service account, you will receive a client ID and client secret, which you will use to generate OAuth access tokens for Atlas API requests.
NOTE: Service account credentials will give anyone access to your MongoDB Atlas resources. It is crucial to securely store your client ID and client secret and never expose them in public source code platforms like GitHub.
Before running any examples, please make sure to execute all prerequisites.
In this tutorial, we will provide steps to make programmatic API requests in different languages:
- Python
- Node.js
Please refer to the Atlas documentation for a complete list of Atlas APIs for languages without an Atlas SDK. You can also use our official Postman integration to explore and interact with the API itself.
The Atlas API authentication process will consist of the following steps, independent of the language and framework:
- Loading credentials using environment variables
- For the purpose of examples, we will use environment variables to store the client ID and client secret.
- Generating access token
- Depending on your language, some libraries will perform a POST request to the OAuth token endpoint out of the box. In other cases, you will need to make a request yourself. The response from the call will contain the access token that will be used for authentication.
- Using access token
- The access token will be included in the Authorization header of subsequent API requests to authenticate them.
- An access token needs to be regenerated when it expires, and the API returns an HTTP 401 status code.
We will use Python to start with the simplest and most self-contained service account integration example. Python provides many libraries for performing HTTP requests. For instance, we will use the Requests library to handle OAuth 2.0 authentication.
- Install the required packages:
1 pip install requests 2 pip install oauthlib
Step #1: Open your favorite code editor and create a file named atlas_request.py.
Step #2: Copy the content into the new file. Here's what the complete script will look like:
1 import os 2 from requests_oauthlib import OAuth2Session 3 from oauthlib.oauth2 import BackendApplicationClient 4 from requests.auth import HTTPBasicAuth 5 import requests 6 7 # Constants 8 token_path = "/api/oauth/token" 9 api_url = "/api/atlas/v2/" 10 client_id = os.environ["MONGODB_ATLAS_CLIENT_ID"] 11 client_secret = os.environ["MONGODB_ATLAS_CLIENT_SECRET"] 12 base_url = "https://cloud.mongodb.com" 13 14 def get_access_token(): 15 # Use BackendApplicationClient for the client credentials grant 16 client = BackendApplicationClient(client_id=client_id) 17 oauth = OAuth2Session(client=client) 18 19 # Prepare Basic Auth credentials 20 auth = HTTPBasicAuth(client_id, client_secret) 21 token_url = f"{base_url}{token_path}" 22 23 # Fetch the token using the proper authentication 24 token = oauth.fetch_token(token_url=token_url, auth=auth) 25 return token['access_token'] 26 27 def fetch_data(): 28 access_token = get_access_token() 29 headers = { 30 "Authorization": f"Bearer {access_token}", 31 "Accept": "application/vnd.atlas.2023-01-01+json" 32 } 33 34 response = requests.get(f"{base_url}{api_url}", headers=headers) 35 response.raise_for_status() 36 37 return response.json() 38 39 if __name__ == "__main__": 40 try: 41 data = fetch_data() 42 print(data) 43 except Exception as e: 44 print(f"Error: {e}")
Step #3: Set the environment variables in your terminal:
1 set +o history # disable history as we're going to paste credentials 2 export SA_CLIENT_ID=your_client_id 3 export SA_CLIENT_SECRET=your_client_secret
Step #4: Run the example:
1 python atlas_request.py
As a result, you should see Response Status: 200 in the console.
Let’s unpack what’s happening in the Python script step by step.
The Python script performs several steps to authenticate with MongoDB Atlas using OAuth2 and query its API.
- We start by loading our credentials from environment variables.
- Environment variables allow us to manage sensitive information, like your MongoDB Atlas client ID and secret, without hard-coding them into your script.
- We retrieve the following variables:
MONGODB_ATLAS_CLIENT_ID
andMONGODB_ATLAS_CLIENT_SECRET
for OAuth2 authentication.
- With our credentials in place, we obtain an access token, essential for making authenticated API requests.
- The get_access_token function:
- We're leveraging the client credentials grant type through the BackendApplicationClient from oauthlib.
- Token management operations are handled entirely by the library.
- Please make sure to always use the latest version of the oauthlib library to avoid potential security issues.
- Using HTTPBasicAuth, we generate the credentials needed to request a token.
- Please note that the access token needs to be periodically updated upon expiry.
- Using the obtained access token:
- First, we grab our access token returned from the get_access_token method.
- Next, we set up our request with proper headers:
- Authorization is set to Bearer {access_token}.
- Accept specifies the MongoDB Atlas API version required to perform requests against Atlas API (application/vnd.atlas.2023-01-01+json).
- The function calls the Atlas API endpoint and awaits the response!
GET
request to the specified Atlas API endpoint ({base_url}/api/atlas/v2/
).
Node.js provides a rich number of libraries for performing HTTP requests. Our example will follow a Node.JS Reference Architecture recommendation by using the Axios npm library.
Axios is a popular promise-based HTTP client for the browser and Node.js. For brevity, the example is written in JavaScript, but it can be adapted to TypeScript by using Axios Typings.
- For existing projects, install the required axios and simple-oauth2 package:
1 npm install —-save axios simple-oauth2
If you are recreating a new project, you need to initialize the package.json file by running:
1 npm init
Step #1: Open your favorite code editor and create a file named atlas_request.js.
Step #2: Copy the content into the new file. Here's what the complete script will look like:
1 const axios = require('axios'); 2 const { ClientCredentials } = require('simple-oauth2'); 3 4 // Can be any API url from https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/ 5 const apiURL = '/api/atlas/v2/'; 6 7 const { MONGODB_ATLAS_CLIENT_ID, MONGODB_ATLAS_CLIENT_SECRET } = process.env; 8 9 var baseUrl = "https://cloud.mongodb.com"; 10 11 // OAuth2 Client Configuration 12 const oauth2Config = { 13 client: { 14 id: MONGODB_ATLAS_CLIENT_ID, 15 secret: MONGODB_ATLAS_CLIENT_SECRET, 16 }, 17 auth: { 18 tokenHost: baseUrl, 19 tokenPath: '/api/oauth/token', 20 }, 21 }; 22 23 // Create OAuth2 Client 24 const oauth2Client = new ClientCredentials(oauth2Config); 25 26 async function fetchWithOAuth2() { 27 try { 28 // Retrieve access token 29 const tokenParams = { 30 }; 31 const tokenResponse = await oauth2Client.getToken(tokenParams); 32 const accessToken = tokenResponse.token.access_token; 33 const headers = { 34 Authorization: `Bearer ${accessToken}`, 35 Accept: 'application/vnd.atlas.2023-01-01+json' 36 } 37 // Make API Request 38 const response = await axios.get(baseUrl + apiURL, { 39 headers: headers 40 }); 41 42 console.log('Response data:', response.data); 43 } catch (error) { 44 console.error('Error during request:', error.message); 45 } 46 } 47 48 fetchWithOAuth2();
Step #3: Set the environment variables in your terminal:
1 set +o history # to disable history for credentials 2 export MONGODB_ATLAS_CLIENT_ID=your_client_id 3 export MONGODB_ATLAS_CLIENT_SECRET=your_client_secret
Step #4: Run example:
1 node atlas-request.js
As a result, I should see the response from the API in the console.
Similar to the Python example, the code will perform several steps that are common for OAuth.
- Loading the environment variables: We retrieve the MONGODB_ATLAS_CLIENT_ID and MONGODB_ATLAS_CLIENT_SECRET variables from the environment.
- For the example, we have chosen to use the simple-oauth2 library. The library allows us to automatically obtain and refresh OAuth2 tokens. To do that, we need to provide a client configuration:
client_id
andclient_secret
from environment variables.auth.tokenHost
references OAuth Token API provided by Atlas (/api/oauth/token) We use that URL for token retrieval.
- Calling simple-oauth2.getToken() to fetch a new access token: On success, this retrieves the access_token from the token response.
- Making an API request:
- We need to set the
Authorization
header containing our freshly generated token. - The endpoint can be changed to query different MongoDB Atlas API resources.
- During multiple requests, the access token might expire and result in a 401 HTTP status code.
- You can configure your application to issue another access token upon expiry.
The Atlas SDK Go provides OAuth authentication using Service Accounts, which is currently available as a preview feature.
Additionally, developers can use the Service Account Management API to create, update, and delete service accounts directly from the SDK.
- Create a go.mod file and install the required package.
1 go mod init example.com/service-accounts 2 go get go.mongodb.org/atlas-sdk/v20241023001/admin
To ensure you are using the latest version of SDK Go, please replace the v20241023001 version string with the latest version from the SDK Go releases.
Step #1: Create a new file named atlas_request.go in the editor of your choice.
Step #2: Paste the following content into the new file:
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 9 "go.mongodb.org/atlas-sdk/v20241113001/admin" 10 ) 11 12 // Example for Using Service Account for listing Atlas Projects. 13 func main() { 14 // Fetch clientID and clientSecret from environment variables 15 clientID := os.Getenv("MONGODB_ATLAS_CLIENT_ID") 16 clientSecret := os.Getenv("MONGODB_ATLAS_CLIENT_SECRET") 17 18 if clientID == "" || clientSecret == "" { 19 log.Fatal("Missing required environment variables") 20 } 21 22 ctx := context.Background() 23 sdk, err := admin.NewClient( 24 admin.UseBaseURL(host), 25 //Out-of-the-box support for OAuth in the SDK 26 admin.UseOAuthAuth(ctx, clientID, clientSecret), 27 ) 28 if err != nil { 29 log.Fatalf("Error: %v", err) 30 } 31 32 orgs, _, err := sdk.OrganizationsApi.ListOrganizations(ctx).Execute() 33 if err != nil { 34 log.Fatalf("Error: %v", err) 35 } 36 if orgs.GetTotalCount() == 0 { 37 log.Fatalf("no orgs") 38 } 39 fmt.Println("Successfully used Service Account") 40 }
Step #3: Set the environment variables in your terminal:
1 export MONGODB_ATLAS_CLIENT_ID=your_client_id 2 export MONGODB_ATLAS_CLIENT_SECRET=your_client_secret 3 export MONGODB_ATLAS_ORG=your_org_id
Step #4: Run the example:
1 go run atlas_request.go
As a result, you should see the Successfully used Service Account in your terminal.
The code is using the admin.UseOAuthAuth(ctx, clientID, clientSecret) method provided by the SDK to automatically authenticate using Service Accounts. No more actions are required.
Additionally, to authenticate, SDK Go provides an example of Service Account Management API , which will enable you to manage Service Accounts.
This tutorial demonstrated how to set up Service Accounts and interact with the Atlas API using SDK Go, Node.js, and Python. With these examples, you can integrate Atlas API operations into your applications written in those languages.
Service Accounts and the Atlas Administration API provide a new set of possibilities for managing your MongoDB Atlas resources. By leveraging OAuth2 with the Client Credentials flow, developers can integrate programmatic access into their applications and automation workflows while adhering to industry-standard security practices.
Whether you’re automating deployments, managing databases, or building operational tools, the Atlas Administration API, combined with Service Accounts, provides a robust foundation for seamless MongoDB Atlas integration.
Warning:
- Always safeguard your credentials using environment variables or secure storage.
- Regularly rotate and revoke Service Account secrets to maintain security.
- Explore the Atlas Go SDK, Postman Collection, and API documentation for more capabilities tailored to your use case.
Top Comments in Forums
There are no comments on this article yet.