I have a need to ratelimit users who authenticate with user tokens.
However, I don’t want to limit normal users.
I don’t see any option rather than setting global throttling classes on settings.py and per view throttle_classes.
Is there any way to do this properly?
Thanks
What do you mean by “normal users” here? Are you referring to AnonymousUser? (Unauthenticated) Or are you referring to users authenticating via a different mechanism?
The Setting the throttling policy docs appears to cover the case where you want to throttle anonymous users at a different rate than authenticated users.
Hi, Ken!
I did not mean Anonymous Users.
I have User Token that is used for TokenAuthentication.
So users with the key can access our api alongside with normal users who log in with username and password in conventional way.
I want to restrict those token users 5 requests per second.
I can set throttling globally or per views but I don’t know how to use throttle only for those token users.
There are hundreds of views inside the app so I cannot touch them respectively.
That’s my problem
Hope this makes sense.
Sure, that makes sense. I can see how using request.auth you should be able to identify those users authenticating via token.
It looks like you do this with a custom throttle class that subclasses SimpleRateThrottle. (I was originally thinking that you would subclass UserRateThrottle, but URT only supplies a get_cache_key
method, which is what you need to replace anyway. So there’s no need to inherit from URT. However, URT is a perfect example showing what basically needs to be done, so I would definitely recommend reading the source for it and understanding how it works.)
I was originally subclassing UserRateThrottle.
Seems like I need to go down to the bottom(base RateThrottle class) to see what’s going on and what is possible.
Thanks for the help.
I will let you know once I figure it out.
I guess people will need to do the same thing in many cases if they work on big and sophisticated systems.
Hi, Ken!
Yes, so I overrode allow_request method of BaseThrottle class and that solved my issue.
I checked if the request authentication header contains the keyword of TokenAuthentication class and then ignored which do not contain it.
It works well
Your idea was correct
Thanks