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

Learn why MongoDB was selected as a leader in the 2024 Gartner® Magic Quadrant™
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Center
chevron-right
Developer Topics
chevron-right
Products
chevron-right
MongoDB
chevron-right

MongoDB Atlas Authentication Using Service Accounts (OAuth)

Wojciech Trocki9 min read • Published Jan 23, 2025 • Updated Jan 23, 2025
JavaScriptGoPythonMongoDB
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
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.

What are Service Accounts?

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.
Infographic describing MongoDB Atlas Programmatic Authentication with Service AccountsProgrammatic Authentication with MongoDB Atlas enables secure service account integration for automation.Features:- Leverage service accounts to handle automated processes effectively. Improve CI/CD workflows and support AI training through robust API interactions.- Automate the creation and management of clusters, ensuring reliable backups, scaling, and monitoring without the need for manual setup. Utilize OAuth in programming languages of your choice- Utilize established OAuth clients like Python, JavaScript, and Golang to securely link with MongoDB Atlas and streamline data operations.- Implement detailed access controls for service accounts. Assign roles for reading, writing, or admin tasks, following the least privilege principle for better security.

Prerequisites

Before you begin, ensure you have the following:
  1. 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.
  2. A service account with a client ID and client secret.
  3. To create a service account, follow the instructions provided in the Service Accounts.
    1. For this tutorial, your service account will require a ORG_READ_ONLY role.
    2. 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.

TL;DR?

All examples are available under the GitHub repository for direct consumption.
Before running any examples, please make sure to execute all prerequisites.

Choosing your language

In this tutorial, we will provide steps to make programmatic API requests in different languages:
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.

Authentication process

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.
    • For production usage, please follow OWASP recommendation for secrets.
  • 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.
  • Optionally, we can revoke the created OAuth token when it is no longer needed.

Service accounts with Python

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.

Prerequisites

  1. Ensure you have installed Python 3.8 or later on your machine.
  2. Install the required packages:
1pip install requests
2pip install oauthlib

Creating our example

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:
1import os
2from requests_oauthlib import OAuth2Session
3from oauthlib.oauth2 import BackendApplicationClient
4from requests.auth import HTTPBasicAuth
5import requests
6
7# Constants
8token_path = "/api/oauth/token"
9api_url = "/api/atlas/v2/"
10client_id = os.environ["MONGODB_ATLAS_CLIENT_ID"]
11client_secret = os.environ["MONGODB_ATLAS_CLIENT_SECRET"]
12base_url = "https://cloud.mongodb.com"
13
14def 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
27def 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
39if __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:
1set +o history # disable history as we're going to paste credentials
2export SA_CLIENT_ID=your_client_id
3export SA_CLIENT_SECRET=your_client_secret
Step #4: Run the example:
1python atlas_request.py
As a result, you should see Response Status: 200 in the console.

Understanding the script

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 and MONGODB_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/).

Service accounts with Node.js

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.

Prerequisites

  1. Ensure you have Node.js and npm installed on your machine.
  2. 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:
1npm init

Procedure

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:
1const axios = require('axios');
2const { ClientCredentials } = require('simple-oauth2');
3
4// Can be any API url from https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/
5const apiURL = '/api/atlas/v2/';
6
7const { MONGODB_ATLAS_CLIENT_ID, MONGODB_ATLAS_CLIENT_SECRET } = process.env;
8
9var baseUrl = "https://cloud.mongodb.com";
10
11// OAuth2 Client Configuration
12const 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
24const oauth2Client = new ClientCredentials(oauth2Config);
25
26async 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
48fetchWithOAuth2();
Step #3: Set the environment variables in your terminal:
1set +o history # to disable history for credentials
2export MONGODB_ATLAS_CLIENT_ID=your_client_id
3export MONGODB_ATLAS_CLIENT_SECRET=your_client_secret
Step #4: Run example:
1node atlas-request.js
As a result, I should see the response from the API in the console.

Understanding the script

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 and client_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.

Service accounts with Go applications

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.

Prerequisites

  1. Ensure you have Go 1.22 or later installed on your machine.
  2. Create a go.mod file and install the required package.
1go mod init example.com/service-accounts
2go 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.

Creating Go example

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:
1package main
2
3import (
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.
13func 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:
1export MONGODB_ATLAS_CLIENT_ID=your_client_id
2export MONGODB_ATLAS_CLIENT_SECRET=your_client_secret
3export MONGODB_ATLAS_ORG=your_org_id
Step #4: Run the example:
1go 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.

Closing remarks

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.
Questions? Comments? Join us in the MongoDB Developer Community.
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
Quickstart

Java - MongoDB Multi-Document ACID Transactions


Mar 01, 2024 | 10 min read
News & Announcements

MongoDB 3.6: Here to SRV you with easier replica set connections


Sep 23, 2022 | 4 min read
Tutorial

Use MongoDB as the Data Store for your Strapi Headless CMS


Sep 23, 2022 | 8 min read
Article

Aggregation Pipeline: Applying Benford's Law to COVID-19 Data


Jan 26, 2023 | 16 min read
Table of Contents