Open himalacharya opened 3 years ago
@himalacharya did you find a solution to your problem? can you share here, if it was related to slowapi?
The problem is that user information cann't be decoded from expired token. However, above problem is solved by try except method.
class LimiterClass:
def __init__(self):
#redis used locally
self.limiter = Limiter(key_func=get_user_id_or_ip, strategy="moving-window", default_limits=[DEFAULT_RATE_LIMIT])
def get_user_id_or_ip(request : Request):
authorize = AuthJWT(request) # initial instance fastapi-jwt-auth
try:
#URL_Path is to find refresh endpoint
url_path= request.url.path
if re.search(r'/refresh$',url_path): #refresh - Endpoint for refresh token
#Find refresh token from Authorization headers
authorize.jwt_refresh_token_required()
else:
#If JWT Token is present then get_jwt_object otherwise retrun client IP address
authorize.jwt_optional() # for validation jwt token
return decrypt_data(authorize.get_jwt_subject()) or request.client.host #decrypt-data: Decrypts user
except AuthJWTException:
return request.client.host
For unexpired token, it ratelimits user and for expired tokens , it ratelimits client IP address. For no token, ratelimits client IP address
My concern with your fix is that you seem to be mixing access control into rate-limiting, which could have security implications. In my mind, your access control layer should block the request if the access token is expired, and slowapi should never even see the request.
Looking at your problem again, have you tried using 2 limiter instances? one for each type of endpoint? I've not tried this before, so I have no idea if it works, but you should be able to share the data store between them, and it might solve your problem.
@himalacharya Is this still an issue?
I am rate limiting on two approaches: i)based on IP address (for endpoint having no access token) Works fine ii) based on user id ( obtained from JWT token) I have used https://pypi.org/project/fastapi-jwt-auth/ for JWTAuth. On the basis of #25 , in limiter.py
This works fine on unexpired JWT access token and ratelimits user. But when JWT access token expires, then it throws an error.
When accesstoken expires, I need to return HTTP 403 Forbidden access message.