We have API application, which uses many customers. Every customer have API token, which he passed in GET
request.
Example from access log:
GET /api/token=FhrHd25Sk6REmwqn32Ssdf/bla?/bla/bla
We want to create whitelist for tokens and limit the number of connections per second for each of the tokens using nginx.
Can you advise something on the implementation of this task?
The limit_req
directive controls the maximum connections per second for various keys (in this case the key is the API token). See this document for details.
You can extract the API token by using a map
directive. See this document for details.
For example:
map $request_uri $token {
~/token=freepass/ '';
~/token=(?<thetoken>[^/]+)/ $thetoken;
default 'everybody';
}
limit_req_zone $token zone=one:10m rate=1r/s;
server {
...
limit_req zone=one;
...
}
In the above example, the token "freepass" will have unlimited access as it does not define a value for the key. The token is extracted using a named capture. The default clause places requests with no defined token into the same key, which may or may not be what you want, as those requests will be severely limited.