TIL : Using python decorators to secure method invocation.
Coming from a Java background, I began to explore concepts similar to method level annotations, so that I can apply re-usable methods to solve this problem
Problem : I have to secure a api call with logic to inspect the headers for an auth token and then perform validation logic
Q. Why do i need a common solution?
A. I cannot possibly put validation logic across 24 methods in three classes of controllers.
I relied on these links to help me with the solution
How to Write a Decorator in Python Flask to Check Logged In Status
If you’re writing a web app, chances are there are that there are endpoints which you want to restrict access to based…
How to implement login required decorator in Flask
I would place the following decorator function in somewhere common def validate_api_token(validation_func): def…
The solution is as follows
def decorated_function(*args, **kws):
request = args
if not 'X-Auth-Token' in request.headers:
return responses.error_response("Un-Authorized Request: %s" % str("Missing Token"),
error_code='401')is_valid_api_token = _token_validation_func(request.headers["X-Auth-Token"])
return f(*args, **kws)return responses.error_response("Un-Authorized Request: %s" % str("Invalid Token"),
return decorated_function"""Validates the JWT token Logic
# Validation logic as per business requirementsreturn is_valid
And then use the