Search code examples
pythonapiflasktokenrestful-authentication

itsdangerous.BadSignature error in token integration using TimedJSONWebSerializer - App Backend Server?


I am authenticating the user by a secret_key known only to the backend and the client side and passed through the headers in Postman. My code so far is as follows:

from itsdangerous import TimedJSONWebSignatureSerializer
from constants import SECRET_KEY

@app.route('/authUser', methods=['POST'])
def authUser():
    secret_key = request.headers['secret_key']

    if secret_key is None:
        return "400"
    elif secret_key != SECRET_KEY: # SECRET_KEY is a constant that has been imported from constants.py
        return "400"
    else:
        s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=3600)
        token = s.dumps({'user_id' : user_id})
        print (s.loads(token))
        return token

This code throws the following error:

Traceback (most recent call last):

  File "C:/Users/vaibhav/PycharmProjects/Coding/Coding.py", line 15, in <module>
    print (s.loads(token))
  File "C:\Users\vaibhav\Anaconda\lib\site-packages\itsdangerous.py", line 798, in loads
    self, s, salt, return_header=True)
  File "C:\Users\vaibhav\Anaconda\lib\site-packages\itsdangerous.py", line 752, in loads
    self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
  File "C:\Users\vaibhav\Anaconda\lib\site-packages\itsdangerous.py", line 377, in unsign
    payload=value)
itsdangerous.BadSignature: Signature 'Ch8y6BDMIIBdIGM0lmjdAimINvP3PnUmBpOp-jDW18w' does not match

If I change the line:

s = TimedJSONWebSignatureSerializer(app.config['SECRET-KEY'], expires_in=3600)

to this:

s = TimedJSONWebSignatureSerializer('SECRET-KEY', expires_in=3600)

The code works without a problem.

QUETSION : Please tell me why this works as according to Configuration Handling, app.config('SECRET-KEY') returns a secret key as well.

enter image description here

I referred to this website for learning token authentication:

RESTful Authentication with Flask
Thanks in advance!


Solution

  • Can you first make sure you set the secret key, like

    app.secret_key = 'whatever the secret is'
    

    This will initialize the secret.