Navigation

API Key Authentication

MongoDB Stitch provides the option to authenticate with your Stitch application using API keys.

There are two types of API keys in MongoDB Stitch: server keys and user keys. Server keys are generated in the Stitch admin console, and they are associated with a specially created Stitch user with the type server. Server key authentication is most useful for authenticating other non-Stitch services in your application’s infrastructure with your Stitch application.

User keys are generated from within the client SDKs, and they are associated with an existing MongoDB Stitch user. User keys are useful when building applications where end users own or manage many different devices that are talking to Stitch.

For example, an IoT application may enable end users to manage a number of devices from a web or mobile application. Using the Stitch SDKs, that application can issue API keys that the devices can use to communicate with your Stitch application on behalf of the end user. The IoT devices in this scenario would use a Stitch client SDK to authenticate with and communicate with Stitch.

Enable API Key Authentication

To enable API key authentication,

  1. Select Users from the left-side navigation.
  2. Select the Providers tab.
  3. For API Keys, click the Edit button.
  4. Switch the Provider Status toggle to enabled. This allows users to authenticate with both user API keys and server API keys.

Authenticating with API Keys

The process for authenticating via an API key is the same regardless of whether you are using a server key or user key.

To incorporate API key authentication into a web or Node.js application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. If using an HTML file, include the MongoDB Stitch library .

    <script defer type="text/javascript" src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
    
  2. Build a StitchClient object in your application.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To authenticate using an API key, the StitchClient class provides the authenticate() function. Provide the string 'apiKey' as the first parameter to indicate that you are using API Key authentication, and provide the API key you created earlier as the second parameter.

    Warning

    If using a server API key, be sure to keep it a secret, and never place it in a publicly accessible location. For example, avoid storing your API key in source code repositories or revealing it on online code-sharing platforms such as Stack Overflow.

    yourStitchClient.authenticate('apiKey', '<your-api-key>').then(userId => {
      console.log('Successfully authenticated as ' + userId);
    }).catch((err) => {
      console.error('Error authenticating: ' + err);
    });
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

To incorporate API key authentication into an Android application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Import the MongoDB Stitch client and API key authentication provider.

    import com.mongodb.stitch.android.StitchClient;
    import com.mongodb.stitch.android.auth.apiKey.APIKeyProvider;
    
  2. Include the code to instantiate a StitchClient.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To authenticate using an API key, the StitchClient provides the logInWithProvider() method, which you can provide with an APIKeyProvider.

    Warning

    Although it is possible to authenticate using a server key in the mobile SDKs, we do not recommend this. In most cases, end users of your client application should be authenticating using user API keys, or another provider. Server keys should be used to authenticate services in your application’s infrastructure, not end users.

    yourStitchClient.logInWithProvider(new APIKeyProvider("<your-api-key>")).addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull final Task<String> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully logged in as user " + task.getResult());
            } else {
                Log.e("stitch", "Error logging in with API key auth:", task.getException());
            }
        }
    });
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

To incorporate API key authentication into an iOS application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Include the core MongoDB Stitch library.

    import StitchCore
    
  2. Instantiate a StitchClient: object in your application.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To login with an API key, the StitchClient provides the login() method, which you can provide with an ApiKeyAuthProvider.

    Warning

    Although it is possible to authenticate using a server key in the mobile SDKs, we do not recommend this. In most cases, end users of your client application should be authenticating using user API keys, or another provider. Server keys should be used to authenticate services in your application’s infrastructure, not end users.

    yourStitchClient.login(withProvider: ApiKeyAuthProvider(key: "<your-api-key>"))
        .done { (userId: String) in
            print("Successfully logged in as user \(userId)")
        }.catch { error in
            print("Error logging in with API key auth: \(error)")
    }
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

Managing API Keys

If your application authenticates users with user API keys, another component of your application must provide a way for users to manage their API keys. If your application authenticates using server API keys, you must create and manage the keys in the MongoDB Stitch admin console.

These separate processes are described in the next few subsections.

Managing Server API Keys

The interface for creating and managing server API keys is in the MongoDB Stitch admin console. To manage server API keys,

  1. Navigate to the settings interface of the API Key authentication provider. This is the same interface where you enabled API Key authentication.
  2. To create a server API key:
    1. Click the CREATE API KEY button.
    2. Enter a name for the API key in the Name text box. This will be the name exposed in the metadata field of the Stitch user associated with this API key.
    3. Click Save.
    4. Record the resulting alphanumeric string. This is the API key that you will provide to your application when authenticating. This will be the only time you can see the generated API key.
  3. To toggle whether a server API key is enabled or not, use the slider to the left of the key’s name.
  4. To delete a server API key, click the minus button to the right of the key’s name.

Managing User API Keys

Each of the client SDKs includes the methods you need for issuing and managing user API keys. To issue and manage user API keys, you must first be authenticated as an existing MongoDB Stitch user via a different authentication provider. A user can create and associate up to 20 user API keys with their account.

Note

If you are authenticated as a particular user via a user API key, server API key, or via the anonymous authentication provider, you will not be able to create or manage API keys for that user. The management methods are only available when authenticated as another provider.

To create and manage API keys in a web or Node.js application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Build a StitchClient object in your application.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  2. Authenticate with MongoDB Stitch using any authentication provider of your choice, except for anonymous authentication or API key authentication.

    yourStitchClient.authenticate('<provider-of-your-choice>', '<potential-additional-arguments>').then(userId => {
      console.log('Successfully authenticated as', userId);
    }).catch((err) => {
      console.error('Error authenticating:', err);
    });
    
  3. Create a user API key by calling the createApiKey() method on the StitchClient.

    yourStitchClient.createApiKey('<name-of-the-api-key').then(result => {
      console.log('Successfully created new API key: ', result);
    }).catch(err => {
      console.error('Error creating API key:', err);
    });
    

    createApiKey() returns a promise that resolves to a JavaScript object of the following structure:

    {
       _id: "<unique-id-for-the-key>",
       key: "<the-actual-api-key>",
       name: "<name-of-the-api-key>",
       disabled: false
    }
    

    This will be the only time the full API key will be returned by MongoDB Stitch. If the key is lost or forgotten after this point, a new key must be generated and the old key shoud be disabled or deleted.

  4. Get a list of all existing user API keys for a particular user by calling the getApiKeys() method on the StitchClient.

    yourStitchClient.getApiKeys().then(result => {
      console.log('Successfully got list of API keys: ', result);
    }).catch(err => {
      console.error('Error fetching API keys:', err);
    });
    

    getApiKeys() returns a promise that resolves to an array of JavaScript objects with the following structure:

    [
      {_id: "<unique-id>", name: "<name-of-the-api-key>", disabled: false},
      {_id: "<unique-id>", name: "<name-of-the-api-key>", disabled: true},
      {_id: "<unique-id>", name: "<name-of-the-api-key>", disabled: false},
      ...
    ]
    
  5. You can also fetch a particular API key by its _id by calling getApiKeyByID().

    yourStitchClient.getApiKeyByID().then(result => {
      console.log('Successfully fetched API key: ', result);
    }).catch(err => {
      console.error('Error fetching API key:', err);
    });
    

    getApiKeyByID() returns a promise that resolves to a JavaScript objects describing the key with the following structure:

    {
       _id: "<unique-id>",
       name: "<name-of-the-api-key>",
       disabled: false
    }
    

    Note that the actual API key is omitted.

  6. To disable a specific user API key without deleting it, call the disableApiKeyByID() method on the StitchClient.

    yourStitchClient.disableApiKeyByID("<api-key-unique-id>").then(() => {
      console.log('Successfully disabled API key');
    }).catch(err => {
      console.error('Error disabling API key:', err);
    });
    
  7. To enable a specific user API key after it has been disabled, call the enableApiKeyByID() method on the StitchClient.

    yourStitchClient.enableApiKeyByID("<api-key-unique-id>").then(() => {
      console.log('Successfully enabed API key');
    }).catch(err => {
      console.error('Error deleting API key:', err);
    });
    
  8. To delete a specific user API key, call the deleteApiKeyByID() methodon the StitchClient.

    yourStitchClient.deleteApiKeyByID("<api-key-unique-id>").then(() => {
      console.log('Successfully deleted API key');
    }).catch(err => {
      console.error('Error deleting API key:', err);
    });
    

To create and manage API keys in an Android application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Import the MongoDB Stitch client, API key authentication provider, and APIKey class.

    import com.mongodb.stitch.android.StitchClient;
    import com.mongodb.stitch.android.auth.apiKey.APIKey;
    import com.mongodb.stitch.android.auth.apiKey.APIKeyProvider;
    
  2. Include the code to instantiate a StitchClient.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. Authenticate with MongoDB Stitch using any authentication provider of your choice, except for anonymous authentication or API key authentication.

    yourStitchClient.logInWithProvider(new ProviderOfYourChoice()).addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull final Task<String> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully logged in as user " + task.getResult());
            } else {
                Log.e("stitch", "Error logging in:", task.getException());
            }
        }
    });
    
  4. Create a user API key by calling the createApiKey() method on the StitchClient’s Auth object.

    yourStitchClient.getAuth().createApiKey("<name-of-the-api-key>").addOnCompleteListener(new OnCompleteListener<APIKey>() {
        @Override
        public void onComplete(@NonNull final Task<APIKey> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully created API key: " + task.getResult().getKey());
            } else {
                Log.e("stitch", "Error creating API key:", task.getException());
            }
        }
    });
    

    createApiKey() returns a Task that resolves to a an APIKey object. In this case, the key’s getKey() method will not return an empty string.

    This will be the only time the full API key will be returned by MongoDB Stitch. If the key is lost or forgotten after this point, a new key must be generated and the old key shoud be disabled or deleted.

  5. Get a list of all existing user API keys for a particular user by calling the fetchApiKeys() method on the StitchClient’s Auth object.

    yourStitchClient.getAuth().fetchApiKeys().addOnCompleteListener(new OnCompleteListener<java.util.List<APIKey>>() {
        @Override
        public void onComplete(@NonNull final Task<java.util.List<APIKey>> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully fetched API keys: " + task.getResult());
            } else {
                Log.e("stitch", "Error fetching API keys:", task.getException());
            }
        }
    });
    

    fetchApiKeys() returns a Task that resolves to an array of APIKey objects. In this case, each key’s getKey() method will return an empty string.

  6. You can also fetch a particular API key by its unique ID by calling fetchApiKey().

    yourStitchClient.getAuth().fetchApiKey("<api-key-unique-id>").addOnCompleteListener(new OnCompleteListener<APIKey>() {
        @Override
        public void onComplete(@NonNull final Task<APIKey> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully fetched API key: " + task.getResult());
            } else {
                Log.e("stitch", "Error fetching API key:", task.getException());
            }
        }
    });
    

    getApiKeyByID() returns a Task that resolves to a an APIKey object. In this case, the key’s getKey() method will return an empty string.

  7. To disable a specific user API key without deleting it, call the disableApiKey() method on the StitchClient’s Auth object.

    yourStitchClient.getAuth().disableApiKey("<api-key-unique-id>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully disabled API key");
            } else {
                Log.e("stitch", "Error disabling API key:", task.getException());
            }
        }
    });
    
  8. To enable a specific user API key after it has been disabled, call the enableApiKey() method on the StitchClient’s Auth object.

    yourStitchClient.getAuth().enableApiKey("<api-key-unique-id>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully enabled API key");
            } else {
                Log.e("stitch", "Error enabling API key:", task.getException());
            }
        }
    });
    
  9. To delete a specific user API key, call the deleteApiKey() method on the StitchClient’s Auth object.

    yourStitchClient.getAuth().deleteApiKey("<api-key-unique-id>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully deleted API key");
            } else {
                Log.e("stitch", "Error deleting API key:", task.getException());
            }
        }
    });
    

To create and manage API keys in an iOS application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Include the core MongoDB Stitch library.

    import StitchCore
    
  2. Instantiate a StitchClient: object in your application.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. Authenticate with MongoDB Stitch using any authentication provider of your choice, except for anonymous authentication or API key authentication.

    yourStitchClient.login(withProvider: ProviderOfYourChoice())
        .done { (userId: String) in
            print("Successfully logged in as user \(userId)")
        }.catch { error in
            print("Error authenticating: \(error)")
    }
    
  4. Create a user API key by calling the createApiKey() method on the StitchClient’s auth property.

    yourStitchClient.auth?.createApiKey(name: "<name-of-the-api-key>")
       .done { (apiKey: ApiKey) in
          print("Successfully created new API key: \(apiKey.key!)")
       }.catch{ error in
          print("Error creating API key: \(error)")
    }
    

    createApiKey() returns a promise that resolves to a ApiKey struct where there is a value for the optional key property.

    This will be the only time the full API key will be returned by MongoDB Stitch. If the key is lost or forgotten after this point, a new key must be generated and the old key shoud be disabled or deleted.

  5. Get a list of all existing user API keys for a particular user by calling the fetchApiKeys() method on the StitchClient’s auth property.

    yourStitchClient.auth?.fetchApiKeys()
       .done { (apiKeys: [ApiKey]) in
          print("Successfully got list of API keys: \(apiKeys)")
       }.catch{ error in
          print("Error fetching API keys: \(error)")
    }
    

    fetchApiKeys() returns a promise that resolves to an array of ApiKey ApiKey structs where the key property of each is nil.

  6. You can also fetch a particular API key by its unique ID by calling fetchApiKey().

    yourStitchClient.auth?.fetchApiKey(id: "<api-key-unique-id>")
       .done{ (apiKey: ApiKey) in
          print("Successfully fetched API key: \(apiKey)")
       }.catch{ error in
          print("Error fetching API key: \(error)")
    }
    

    fetchApiKey() returns a promise that resolves to an ApiKey ApiKey struct where the key property is nil.

  7. To disable a specific user API key without deleting it, call the disableApiKey() method on the StitchClient’s auth property.

    yourStitchClient.auth?.disableApiKey(id: "<api-key-unique-id>")
       .done{
          print("Successfully disabled API key")
       }.catch{ error in
          print("Error disabling API key: \(error)")
    }
    
  8. To enable a specific user API key after it has been disabled, call the enableApiKey() method on the StitchClient’s auth property.

    yourStitchClient.auth?.enableApiKey(id: "<api-key-unique-id>")
       .done{
          print("Successfully enabled API key")
       }.catch{ error in
          print("Error enabling API key: \(error)")
    }
    
  9. To delete a specific user API key, call the deleteApiKey() method on the StitchClient’s auth property.

    yourStitchClient.auth?.deleteApiKey(id: "<api-key-unique-id>")
       .done{
          print("Successfully deleted API key")
       }.catch{ error in
          print("Error deleting API key: \(error)")
    }