laurentS / slowapi

A rate limiter for Starlette and FastAPI
https://pypi.org/project/slowapi/
MIT License
1.21k stars 77 forks source link

How to rate limit based on [user id/Token] #92

Open alexjolig opened 2 years ago

alexjolig commented 2 years ago

I need to implement the rate limitation based on JWT token. But in utils.py I can only see functions to get user's ip address. So is that possible to customize this. For example I can get the user info from request.state.user. How can I limit based on that?

laurentS commented 2 years ago

I think this issue https://github.com/laurentS/slowapi/issues/13 might be what you're after.

alexjolig commented 2 years ago

Thanks @laurentS . So if I want to limit based on JWT token, should I do it like this?

@limiter.limit(get_jwt_token):
def some_request(request: Request):
    pass
mallorbc commented 2 years ago
def get_limit_for_user():
    request = _request_ctx_var.get()
    key = request.cookies.get("key")

You have to pass values through cookies. In the body it will not work due to asyc.