Navigation

API Key Authentication

Overview

The API Key authentication provider allows users to log in using generated keys. There are two types of API keys in MongoDB Stitch: server keys and user keys.

Server Keys

Server keys are generated centrally in the Stitch UI and are associated with automatically created Stitch server users. Provide a server key to external applications and services to allow them to authenticate directly with Stitch.

User Keys

User keys are generated for specific application users by the client SDKs. You can allow devices or services to communicate with Stitch on behalf of a user by associating a unique user key with each device.

User keys are always associated with a user object created by another authentication provider. Each user can associate up to 20 user keys with their account.

Configuration

You can enable and configure the API Key authentication provider from the Stitch UI by selecting API Keys from the Users > Providers page.

You can enable and configure the API Key authentication provider with stitch-cli by importing an application directory that contains a configuration file for the provider.

The configuration file must be named api-key.json and stored in the /auth_providers directory. Configuration files for the API Key authentication provider have the following form:

/auth_providers/api-key.json
{
  "name": "api-key",
  "type": "api-key",
  "disabled": false
}

Note

The API Key authentication provider does not have any provider-specific configuration options.

Usage

Authenticate with an API Key

To log an existing user in to your application, instantiate UserApiKeyCredential with the user’s email address and password, and provide that credential instance to the StitchAuth.loginWithCredential() method.

const credential = new UserApiKeyCredential("<your-api-key>")

Stitch.defaultAppClient.auth.loginWithCredential(credential)
  .then(authedId => {
     console.log(`successfully logged in with id: ${authedId}`);
  })
  .catch(err => console.error(`login failed with error: ${err}`);

To log a user in using an API key, instantiate an UserApiKeyCredential object with the user’s API key and pass it to the StitchAuth.loginWithCredential() method.

UserApiKeyCredential credential = new UserApiKeyCredential("<your-api-key>")
Stitch.getDefaultAppClient().getAuth().loginWithCredential(credential)
  .addOnCompleteListener(new OnCompleteListener<StitchUser>() {
    @Override
    public void onComplete(@NonNull final Task<StitchUser> task) {
      if (task.isSuccessful()) {
        Log.d("stitch", "Successfully logged in as user " + task.getResult().getId());
      } else {
        Log.e("stitch", "Error logging in with user API key auth:", task.getException());
      }
    }
  }
);

To log an existing user into your application, instantiate UserAPIKeyCredential with the user’s API key and pass it to the StitchAuth.loginWithCredential() method:

let credential = UserAPIKeyCredential.init(withKey: "<your-api-key>")
Stitch.defaultAppClient!.auth.login(withCredential: credential) { result in
  switch result {
  case .success:
      print("Successfully logged in")
  case .failure(let error):
      print("Error logging in with user API key auth: \(error)")
  }
}

Create a User Key

To create a new user key, obtain a UserApiKeyAuthProviderClient instance, and call the createApiKey() method when a user is already logged in with a different, non-anonymous authentication provider. The API key will be associated with the logged in user and can be used to interact with Stitch on their behalf.

Important

Stitch will only shows you the key’s value one time. Make sure to copy the value returned from createApiKey() somewhere safe, otherwise you will need to generate a new key.

const apiKeyClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .createApiKey('<api-key-name>')
  .then(result => {
     const { name, key } = result;
     console.log(`Successfully created user API key ${name} with value ${key}`);
  })
  .catch(err => console.error(err));

To create a new user key, obtain an UserApiKeyAuthProviderClient instance and call the createApiKey() method when a user is already logged in with a different, non-anonymous authentication provider. The API key will be associated with the logged in user and can be used to interact with Stitch on their behalf.

Important

Stitch will only shows you the key’s value one time. Make sure to copy the value returned from createApiKey() somewhere safe, otherwise you will need to generate a new key.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

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

To create a new user key, obtain a UserAPIKeyAuthProviderClient instance, and call the createAPIKey() method when a user is already logged in with a different, non-anonymous authentication provider. The API key will be associated with the logged in user and can be used to interact with Stitch on their behalf.

Important

Stitch will only shows you the key’s value one time. Make sure to copy the value returned from createAPIKey() somewhere safe, otherwise you will need to generate a new key.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient
  .createApiKey(withName: "<name-of-the-api-key>") { result in
  switch result {
  case .success(let apiKey):
      print("Successfully created new API key: \(apiKey.key!)")
  case .failure(let error):
      print("Error creating API key: \(error)")
  }
}

Create a Server Key

To create a new server key, navigate to the API Key authentication configuration page in the Stitch UI and click Create API Key. Enter a unique name for the key and click Save.

Important

Remember to copy the server key’s value as soon as you create it. Once you leave the provider configuration page or disable the key you will not be able to find the value again in the Stitch UI.

Look up an Existing User Key

To get a list of all keys associated with the logged in user, obtain a UserApiKeyAuthProviderClient instance, and call the fetchApiKeys() method.

const apiKeyClient = Stitch.defaultAppClient.auth
   .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .fetchApiKeys()
  .then(keys => keys.forEach(key => {
     const { _id: keyId, name } = key
     console.log(`Found key ${name} with id ${keyId}`)
  })
.catch(err => console.error(`Error authenticating: ${err}`));

To look up a specific key for the logged in user, pass the key’s _id value to the fetchApiKey() method.

const apiKeyClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .fetchApiKey("<api-key-id>")
  .then(key => console.log(`Successfully fetched API key: ${key}`))
  .catch(err => console.error(`Error fetching API key: ${err}`))

To get a list of all keys associated with the logged in user, obtain an UserApiKeyAuthProviderClient instance and call the fetchApiKeys() method.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

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

To look up a specific key for the logged in user, pass the key’s _id value to the fetchApiKey() method.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

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

To get a list of all keys associated with the logged in user, obtain a UserAPIKeyAuthProviderClient instance, and call the fetchAPIKeys() method.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient.fetchAPIKeys() { result in
  switch result {
  case .success(let apiKeys):
      print("Successfully fetched API keys: \(apiKeys)")
  case .failure(let error):
      print("Error creating API keys: \(error)")
  }
}

To look up a specific key for the logged in user, pass the key’s _id value to the fetchAPIKey(withID:_:) method as the withID argument.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient.fetchAPIKey(withID: "<api-key-id>") { result in
  switch result {
  case .success(let apiKey):
      print("Successfully fetched API key: \(apiKey.key!)")
  case .failure(let error):
      print("Error creating API key: \(error)")
  }
}

Enable or Disable an API Key

To disable a specific API key without deleting it, obtain a UserApiKeyAuthProviderClient instance, and call the disableApiKey() method with the key’s _id value.

const apiKeyClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .disableApiKey("<api-key-id>")
  .then(() => console.log('Successfully disabled API key'))
  .catch(err => console.error(`Error disabling API key: ${err}`))

To enable a specific API key that was previously disabled, pass the key’s _id value to the enableApiKey() method.

const apiKeyClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .enableApiKey("<api-key-id>")
  .then(() => console.log('Successfully enabed API key'))
  .catch(err => console.error(`Error deleting API key: ${err}`))

To disable a specific API key without deleting it, obtain an UserApiKeyAuthProviderClient instance and pass the key’s _id value to the disableApiKey() method.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

apiKeyClient.disableApiKey("<api-key-id>")
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull final Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully disabled API key");
            } else {
                Log.e("stitch", "Error disabling API key:", task.getException());
            }
        }
    });

To enable a specific API key that was previously disabled, pass the key’s _id value to the enableApiKey() method.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

apiKeyClient.enableApiKey("<api-key-id>")
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull final Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully enabled API key");
            } else {
                Log.e("stitch", "Error enabling API key:", task.getException());
            }
        }
    });

To disable a specific API key without deleting it, obtain a UserAPIKeyAuthProviderClient instance, and pass the key’s _id value to the disableAPIKey(withID:_:) method as the withID argument.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient.disableAPIKey(withID: "<api-key-id>") { result in
  switch result {
  case .success:
      print("Successfully disabled API key")
  case .failure(let error):
      print("Error disabling API key: \(error)")
  }
}

To enable a specific API key that was previously disabled, pass the key’s _id value to the enableAPIKey(withID:_:) Protocols/UserAPIKeyAuthProviderClient.html#/s:10StitchCore28UserAPIKeyAuthProviderClientP06enableD0y10MongoSwift8ObjectIdV6withID_yAA0A6ResultOyytGctF> method as the withID argument.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient.enableAPIKey(withID: "<api-key-id>") { result in
  switch result {
  case .success:
      print("Successfully enabled API key")
  case .failure(let error):
      print("Error enabling API key: \(error)")
  }
}

Delete an API Key

To delete a specific API key, obtain a UserApiKeyAuthProviderClient instance, annnd pass the key’s _id value to the deleteApiKey() method.

const apiKeyClient = Stitch.defaultAppClient.auth
   .getProviderClient(UserApiKeyAuthProviderClient.factory);

apiKeyClient
  .deleteApiKey("<api-key-id>")
  .then(() => console.log('Successfully deleted API key'))
  .catch(err => console.error(`Error deleting API key: ${err}`))

To delete a specific API key, obtain an UserApiKeyAuthProviderClient instance and pass the key’s _id value to the deleteApiKey() method.

UserApiKeyAuthProviderClient apiKeyClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserApiKeyAuthProviderClient.factory
);

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

To delete a specific API key, obtain a UserAPIKeyAuthProviderClient instance, and pass the key’s _id value to the deleteAPIKey(withID:_:) method as the withID argument.

let apiKeyClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userAPIKeyClientFactory
)

apiKeyClient.deleteAPIKey(withID: "<api-key-id>") { result in
  switch result {
  case .success:
      print("Successfully deleted API key")
  case .failure(let error):
      print("Error deleting API key: \(error)")
  }
}