JWT decoding in python backend #8807
-
SummaryI am trying to extract access token from the session of the user in the python backend, which is present in the cookie "__Secure-next-auth.session-token". My issue is the code doesn't work. I have even tried hashing the secret key and decoding the cookie. Additional informationAdding the code snippet.
Note:- I am able to get the proper cookie which is present in the header.
def calculate_sha256(self,secret):
"""
Calculate the SHA-256 hash of a secret string.
Args:
secret (str): The input secret string.
Returns:
str: The SHA-256 hash in hexadecimal format.
"""
sha256_hash = hashlib.sha256()
sha256_hash.update(secret.encode('utf-8'))
return sha256_hash.hexdigest()
def _token_decode(self) -> dict:
"""
Decodes the contents of the reauthentication cookie.
Returns
-------
str
The decoded JWT cookie for passwordless reauthentication.
"""
try:
#cookie = self._get_cookie()
cookie = self.get_cookie_value(self.cookie_name )
#jwt = decode(cookie,NEXTAUTH_SECRET,algorithms=['HS256'])
try:
hashedsecret = self.calculate_sha256(NEXTAUTH_SECRET)
# Decode the JWT without verification
decoded_token = pyjwt.decode(cookie, hashedsecret, algorithms=['None'],verify=False)
print("Decoded JWT data:")
print(decoded_token)
except pyjwt.ExpiredSignatureError:
# Handle token expiration if needed
print("Token has expired.")
except pyjwt.DecodeError:
# Handle decoding errors (e.g., invalid token)
print("Token decoding failed or token is invalid.")
except:
return False ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
I got into the same issue, did you solve it? |
Beta Was this translation helpful? Give feedback.
-
thank you! Might it be due to changes in the new implementation of next-auth, AuthJS? |
Beta Was this translation helpful? Give feedback.
-
Auth JS (V5) - "next-auth": "^5.0.0-beta.16" spent 3 hour to figure it out , here is the code to save your time . For Production (https) For Development (http) below example is for http
|
Beta Was this translation helpful? Give feedback.
reverse engineer next-auth code and it works fine now.
Sharing the code :