abersheeran / asgi-ratelimit

A ASGI Middleware to rate limit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ratelimit user_id for JWT access token , IP address for endpoint having not token.

apptechxonia opened this issue · comments

using https://indominusbyte.github.io/fastapi-jwt-auth/ for JWT auth. My requirement is to ratelimit users based on client ip address not having token . For endpoint having access token , user_id is in access token and want to ratelimit that user_id. While using another ratelimiter slowapi, folllowing code worked fine. How to define auth_function while using this ratelimit.

from fastapi_jwt_auth import AuthJWT
from starlette.requests import Request
def get_user_id_or_ip(request: Request):
    authorize = AuthJWT(request)  # initial instance fastapi-jwt-auth
    try:        
         # If JWT Token is present then get_jwt_object otherwise return client IP address
         authorize.jwt_optional()  # for validation jwt token
        return decrypt_data(authorize.get_jwt_subject()) or request.client.host
    except AuthJWTException:
        return request.client.host

In main.py  (using fastApi)
app.add_middleware(
    RateLimitMiddleware,
    authenticate=get_user_id_or_ip,
    backend=RedisBackend(),
    config={
        r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],
        r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],
    },
)