java_small_white Created with Sketch.

Api keys

Generate key - generateSecuredApiKey

When you need to restrict the scope of the Search Key, we recommend to use Secured API Key. You can generate a Secured API Key from the Search Only API Key or any search User API Key

There is a few things to know about Secured API Keys

  • They always need to be generated on your backend using one of our API Client
  • You can generate them on the fly (without any call to the API)
  • They will not appear on the dashboard as they are generated without any call to the API
  • The key you use to generate it needs to become private and you should not use it in your frontend.
  • The generated secured API key will inherit any restriction from the search key it has been generated from

You can then use the key in your frontend code

var client = algoliasearch('YourApplicationID', 'YourPublicAPIKey');

var index = client.initIndex('indexName')

index.search('something', function(err, content) {
  if (err) {
    console.error(err);
    return;
  }

  console.log(content);
});

Filters

Every filter set in the API key will always be applied. On top of that filters can be applied in the query parameters.

//Sync & Async version

// generate a public API key for user 42. Here, records are tagged with:
//  - 'user_XXXX' if they are visible by user XXXX
String publicKey = client.generateSecuredApiKey("YourSearchOnlyApiKey", new Query().setFilters("_tags:user_42"));

Warning:

If you set filters in the key groups:admin, and groups:press OR groups:visitors in the query parameters, this will be equivalent to groups:admin AND (groups:press OR groups:visitors)

Having one API Key per User

One of the usage of secured API keys, is to have allow users to see only part of an index, when this index contains the data of all users. In that case, you can tag all records with their associated user_id in order to add a user_id=42 filter when generating the Secured API Key to retrieve only what a user is tagged in.

Warning

If you’re generating Secured API Keys using the JavaScript client in your frontend, it will result in a security breach since the user is able to modify the filters you’ve set by modifying the code from the browser.

Valid Until

You can set a Unix timestamp used to define the expiration date of the API key

# generate a public API key that is valid for 1 hour:
long validUntil = System.currentTimeMillis()/1000 + 3600
String publicKey = client.generateSecuredApiKey("YourSearchOnlyApiKey", new Query().setValidUntil(validUntil));

Index Restriction

You can restrict the key to a list of index names allowed for the secured API key

# generate a public API key that is restricted to 'index1' and 'index2':
List<String> restrictIndices = new ArrayList<>();
restrictIndices.add('index1');
restrictIndices.add('index2');
String publicKey = client.generateSecuredApiKey("YourSearchOnlyApiKey", new Query().setRestrictIndices(restrictIndices));

Rate Limiting

If you want to rate limit a secured API Key, the API key you generate the secured api key from need to be rate-limited. You can do that either via the dashboard or via the API using the Add API key or Update api key method

User Rate Limiting

By default the rate limits will only use the IP.

This can be an issue when several of your end users are using the same IP. To avoid that, you can set a userToken query parameter when generating the key.

When set, a unique user will be identified by his IP + user_token instead of only by his IP.

This allows you to restrict a single user to performing a maximum of N API calls per hour, even if he shares his IP with another user.

//Sync & Async version

// generate a public API key for user 42. Here, records are tagged with:
//  - 'user_XXXX' if they are visible by user XXXX
String publicKey = client.generateSecuredApiKey("YourSearchOnlyApiKey", new Query().setFilters("_tags:user_42").setUserToken("42"));

Network restriction

For more protection against API key leaking and reuse you can restrict the key to be valid only from specific IPv4 networks

//Sync & Async version

String publicKey = client.generateSecuredApiKey("YourSearchOnlyApiKey", new Query().setRestrictSources("192.168.1.0/24"));

Add API key - addApiKey

To create API keys:

//Sync version

// Creates a new API key that can only perform search actions
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CreateUpdateKey res = client.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey());

// Creates a new API key that can only perform search action on this index
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CreateUpdateKey res = index.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey());
//Async version

// Creates a new API key that can only perform search actions
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CompletableFuture<CreateUpdateKey> res = client.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey().get());

// Creates a new API key that can only perform search action on this index
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CompletableFuture<CreateUpdateKey> res = index.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey().get());
ACLs

You need to specify the set of ACLs the key will have.

The following rights can be used:

  • search: allows to search the index
  • browse: allows to retrieve all index content via the browse API
  • addObject: allows to add/update an object in the index (copy/move index are also allowed with this right)
  • deleteObject: allows to delete objects from the index
  • deleteIndex: allows to delete or clear index content
  • settings: allows to get index settings
  • editSettings: allows to change index settings
  • analytics: allows to retrieve the analytics through the Analytics API
  • listIndexes: allows to list all accessible indices

Avanced Settings

You can also create an API Key with advanced settings:

validity

Add a validity period. The key will be valid for a specific period of time (in seconds).

maxQueriesPerIPPerHour

Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. If the IP at the source of the call did more than this number of calls in the last hour, a 403 code is returned. Defaults to 0 (no rate limit). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index.

Note: If you are sending the query through your servers, you must use the enableRateLimitForward("TheAdminAPIKey", "EndUserIP", "APIKeyWithRateLimit") function to enable rate-limit.

maxHitsPerQuery

Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index.

indexes

Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the ‘*’ character. For example, “dev_*” matches all indices starting with “dev_” and “*_dev” matches all indices ending with “_dev”. Defaults to all indices if empty or blank.

referers

Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using the ‘*’ character. For example, “https://algolia.com/*” matches all referers starting with “https://algolia.com/” and “*.algolia.com” matches all referers ending with “.algolia.com”. If you want to allow the domain algolia.com you can use “*algolia.com/*”. Defaults to all referers if empty or blank.

queryParameters

Specify the list of query parameters. You can force the query parameters for a query using the url string format (param1=X&param2=Y…).

description

Specify a description to describe where the key is used.

//Sync version

// Creates a new API key that is valid for 300 seconds
ApiKey apiKey = new ApiKey();
  .setAcl(Arrays.asList("search")).
  .setMaxHitsPerQuery(20).
  .setMaxQueriesPerIPPerHour(100).
  .setValidity(300).
  .setIndexes(Arrays.asList("myIndex")).
  .setReferers(Arrays.asList("algolia.com/*")).
  .setQueryParameters("typoTolerance=strict&ignorePlurals=false").
  .setDescription("Limited search only API key for algolia.com");

CreateUpdateKey res = client.addKey(apiKey);
System.out.println("Key: " + res.getKey());
//Async version

// Creates a new API key that is valid for 300 seconds
ApiKey apiKey = new ApiKey();
  .setAcl(Arrays.asList("search")).
  .setMaxHitsPerQuery(20).
  .setMaxQueriesPerIPPerHour(100).
  .setValidity(300).
  .setIndexes(Arrays.asList("myIndex")).
  .setReferers(Arrays.asList("algolia.com/*")).
  .setQueryParameters("typoTolerance=strict&ignorePlurals=false").
  .setDescription("Limited search only API key for algolia.com");

CompletableFuture<CreateUpdateKey> res = client.addKey(apiKey);
System.out.println("Key: " + res.get().getKey());

Update api key - updateApiKey

To update the permissions of an existing key:

//Sync version

// Creates a new API key that is valid for 300 seconds
CreateUpdateApiKey res = client.updateApiKey("myAPIKey", new ApiKey().setAcl(Arrays.asList("search")).setValidity(300));

// Update a index specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
CreateUpdateApiKey res = index.updateApiKey("myAPIKey", new ApiKey()
  .setAcl(Arrays.asList("search"))
  .setValidity(300)
  .setMaxQueriesPerIPPerHour(200)
  .setMaxHitsPerQuery(20)
);
//Async version

// Creates a new API key that is valid for 300 seconds
CompletableFuture<CreateUpdateApiKey> res = client.updateApiKey("myAPIKey", new ApiKey().setAcl(Arrays.asList("search")).setValidity(300));

// Update a index specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
CompletableFuture<CreateUpdateApiKey> res = index.updateApiKey("myAPIKey", new ApiKey()
  .setAcl(Arrays.asList("search"))
  .setValidity(300)
  .setMaxQueriesPerIPPerHour(200)
  .setMaxHitsPerQuery(20)
);

To get the permissions of a given key:

//Sync version

// Gets the rights of a key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f");

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107");
//Async version

// Gets the rights of a key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f").get();

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107").get();

Delete api key - deleteApiKey

To delete an existing key:

//Sync & Async version

// Deletes a key
client.deleteKey("f420238212c54dcfad07ea0aa6d5c45f");

// Deletes an index specific key
index.deleteKey("71671c38001bf3ac857bc82052485107");

Get key permissions - getApiKey

To get the permissions of a given key:

//Sync version

// Gets the rights of a key
Optional<ApiKey> apiKey1 = client.getApiKey("f420238212c54dcfad07ea0aa6d5c45f");

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getApiKey("71671c38001bf3ac857bc82052485107");
//Async version

// Gets the rights of a key
Optional<ApiKey> apiKey1 = client.getApiKey("f420238212c54dcfad07ea0aa6d5c45f").get();

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getApiKey("71671c38001bf3ac857bc82052485107").get();

List user keys - listApiKeys

To list existing keys, you can use:

//Sync version

// Lists API Keys
List<ApiKey> apiKeys = client.listKeys();

// Lists API Keys that can access only to this index
List<ApiKey> indexKeys = index.listKeys();
//Async version

// Lists API Keys
CompletableFuture<List<ApiKey>> apiKeys = client.listKeys();

// Lists API Keys that can access only to this index
CompletableFuture<List<ApiKey>> indexKeys = index.listKeys();

Each key is defined by a set of permissions that specify the authorized actions. The different permissions are:

  • search: Allowed to search.
  • browse: Allowed to retrieve all index contents via the browse API.
  • addObject: Allowed to add/update an object in the index.
  • deleteObject: Allowed to delete an existing object.
  • deleteIndex: Allowed to delete index content.
  • settings: allows to get index settings.
  • editSettings: Allowed to change index settings.
  • analytics: Allowed to retrieve analytics through the analytics API.
  • listIndexes: Allowed to list all accessible indexes.