Docs Menu
Docs Home
/
MongoDB Atlas
/ / /

Authenticating with the Atlas Go SDK

The atlas-sdk-go library utilizes Digest authentication as its default authentication method. You can create an API key through the Atlas UI or the Atlas CLI.

To learn more about API authentication, refer to Atlas Administration API Authentication.

To access different parts of the Atlas Admin API, construct a new Atlas SDK client and use its services. For example:

package main
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/atlas-sdk/v20241113004/admin"
)
func main() {
ctx := context.Background()
apiKey := os.Getenv("MONGODB_ATLAS_PUBLIC_KEY")
apiSecret := os.Getenv("MONGODB_ATLAS_PRIVATE_KEY")
sdk, err := admin.NewClient(admin.UseDigestAuth(apiKey, apiSecret))
if err != nil {
log.Fatalf("Error instantiating new client: %v", err)
}
projects, response, err := sdk.ProjectsApi.ListProjects(ctx).Execute()
if err != nil {
log.Fatalf("Could not fetch projects: %v", err)
}
fmt.Printf("Response status: %v\n", response.Status)
fmt.Printf("Projects: %v\n", projects)
}

Atlas SDK Go provides OAuth Authentication using Service Accounts (currently available as a Preview feature) A Service Account implements an OAuth client_credentials grant. For more information about the feature, please refer to Service Account Public documentation.

Authenticating using Service Accounts

package main
import (
"context"
"log"
"os"
"go.mongodb.org/atlas-sdk/v20241113004/admin"
)
func main() {
clientID := os.Getenv("MONGODB_ATLAS_CLIENT_ID")
clientSecret := os.Getenv("MONGODB_ATLAS_CLIENT_SECRET")
if clientID == "" || clientSecret == "" {
log.Fatal("Missing CLIENT_ID or CLIENT_SECRET environment variables")
}
// Using ClientID and ClientSecret. No cache supported (nil).
sdk, err := admin.NewClient(admin.UseOAuthAuth(context.Background(), clientID, clientSecret))
// Make API calls
}

For complete reference implementation, please refer to service account example

Revocation invalidates an OAuth token before its expiration date. This effectively "logs out" the current OAuth client and allows you to configure a new client.

// Sounding code omitted for brevity
revokeConfig := credentials.NewConfig(clientID, clientSecret)
revokeConfig.RevokeToken(context.Background(), &auth.Token{
AccessToken: "yourTokenHere"
});

Service Account OAuth Access Tokens validity is expressed as a number of seconds in the expires_in field. Clients can cache these Access Tokens to mitigate rate limiting and adhere to Access Token limits.

For an example on how to cache and reuse OAuth tokens in the Atlas SDK for Go, see the Service Account OAuth Token Cache Service Account OAuth Token Cache example.

Back

Atlas Go SDK