DEVLOG #5
I found out about JSON Web Tokens (JWT) and how they are used to help in user authentication. I learned more about JWT and found out about the python library Pyjwt. What I made is basically this:
- new
auth_utils.pyfile which contains the following functions:create_access_token,decode_token,get_current_user. - Reformed
authroutes’ response to carry the JWT inside the response body during the signup/login. -
.envfile with a secret key for the JWT.
AUTHENTICATION LOGIC:
The basic logic behind the JWT is that we get the access token and provide every user with their own unique access token at login and signup. This token is then stored in the LoclStorage (for now this is the plan but this being a fronted thing, it is subject to changes) but I am currently wondering about the security of the token being stored in the LocalStorage because a simple JS script can retrieve the token. Also, given that I am not utilizing a refresh token for this version of the program and the 30 day expiration of the access token, the token getting leaked is a big safety hazard so I am looking at utilizing httpOnly cookies instead which cannot be accessed by any rogue JS script running in the browser and would insert the token inside the request header automatically without any backend side JS script having to look into LocalStorage first.
Next, we have a function whose sole job is to authenticate the token and then return the user from the database. This function would be called by all the endpoints the user has access to so that we first authenticate the session of the user before providing the user with any data. This means that if you are on /home and you want to go to /leads, /leads will first authenticate the token given to you and only then will you be able to access that endpoint.
HOW IT WORKS:
-
create_access_token: takes in the user id and uses it along with the secret key to encode the JWT. The payload consists of the user id and the expiration which is set to 30 days from when the token is issued.
ㅤㅤㅤㅤㅤ -
decode_token: simply takes in the token, secret key and the algorithm used for encoding to decode the JWT back into the original payload used during encoding.
ㅤㅤㅤㅤㅤ -
get_current_user: This is the function that authenticates the user session. Basically it has 3 jobs:- Use
HTTPBearer()to extract the authorization credentials from theBearer <Authorization>in the request header. Here, the credentials in the header will be the JWT for the user. - Decode the extracted token using
decode_tokenfunction to get the payload back and handle all the errors likeExpiredSignatureError,InvalidTokenError, etc. - Finally, use the payload to extract the user ID and query the database to find that user and return the user object.
- Use
Now, I will be working on making the leads route which finishes off all the current tables that I have made.
ㅤ
commit: 1ad521f0218e9b6c8f9ebe908e01e6a578c78643
Comments 0
No comments yet. Be the first!
Sign in to join the conversation.