user109321948492842303
user109321948492842303

Reputation: 135

Node.js rate limiter auth token instead of IP address

ive been exploring rate limiting for my mobile app express node.js API. What ive found so far is this solution with express-rate-limit and rate-limit-redis:

> app.use('/account/reset-password', rateLimit({ store: (new
> RedisStore({ //configs here })),   windowMs: 5 * 60000,   max: 12,
> delayMS: 0
> 
> }));

its clean, its nice, it probably works straightfoward, BUT it is not want I want. I want to rate limit my API calls by auth token, not IP address. What would be the simplest way to do this? Im REALLY not trying to write my own solution from scratch this time (Unless thats the ONLY good option), before today I had not even heard of redis etc..

Thanks in advance guys, I hope theres a pretty straight foward answer for this.

Sorry for bad formatting, on iOS.

Upvotes: 4

Views: 1265

Answers (1)

Seth
Seth

Reputation: 10454

You might want to look into one of the suggested alternatives - https://www.npmjs.com/package/express-limiter

The middleware options accepts a lookup value which is used to identify a user.

You can even pass a custom function to the lookup options and do your Auth Token verification there, if it's beyond simply accessing the value from the req object.

limiter({
  lookup: function(req, res, opts, next) {
    if (validApiKey(req.query.api_key)) {
      opts.lookup = 'query.api_key'
      opts.total = 100
    } else {
      opts.lookup = 'connection.remoteAddress'
      opts.total = 10
    }
    return next()
  }
})

Upvotes: 2

Related Questions