Today I Learnt
Published in

Today I Learnt

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

The solution is as follows

def authorize(f):
@wraps(f)
def decorated_function(*args, **kws):
request = args[0]
if not 'X-Auth-Token' in request.headers:
return responses.error_response("Un-Authorized Request: %s" % str("Missing Token"),
http.HTTPStatus.FORBIDDEN,
error_code='401')
is_valid_api_token = _token_validation_func(request.headers["X-Auth-Token"])
if is_valid_api_token:
return f(*args, **kws)
return responses.error_response("Un-Authorized Request: %s" % str("Invalid Token"),
http.HTTPStatus.FORBIDDEN,
error_code='401')
return decorated_function
"""Validates the JWT token Logic
"""
def _token_validation_func(api_token):
# Validation logic as per business requirements
return is_valid

And then use the

@authorized

--

--

--

A curated list of all the TIL’s experienced by me

Recommended from Medium

Launching AWS instance using AWS-CLI

Announcement of NFT Event 2nd week winner [EN/KR]

CSS Cascade summarized

Laravel Package Development

Insights Into Parquet Storage

How I passed the CEH Certification exam

Kotlin Mastery in 2 Months

How should we use GitLab CI/CD pipeline and finally deploy our code to Heroku?- PART-2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Satts B

Satts B

More from Medium

Dataclasses in Python (when, why, how)

How to Upgrade All Python Packages with PIP in 2022?

Persisting Application Data over Time

Import CSV file to DATABASE table in Python