this is the tutorial I'm following, the link
https://thinkster.io/tutorials/django-json-api/authentication
As the title says, I'm getting this error "Invalid format string" at this line:
'exp': int(dt.strftime('%s'))
of _generate_jwt_token.
I looked at the documentation of strftime and there is no such format '%s' there is a uppercase S ('%S'), I changed the format to the uppercase S, but I'm getting an error down the road at trying to decode the Authorization Token where i get the following error
{"user": {"detail": "Invalid authentication. Could not decode token."}}
If I leave the lowercase s I get the "Invalid format string" error.
(authentication/backends.py)
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
(authentication/models.py)
def _generate_jwt_token(self):
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
I expect the following token "Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjo0fQ.TWICRQ6BgjWMXFMizjNAXgZ9T2xFnpGiQQuhRKtjckw" to return a user.
It should be:
token = jwt.encode({
'id': self.pk,
'exp': dt.utcfromtimestamp(dt.timestamp()) #CHANGE HERE
}, settings.SECRET_KEY, algorithm='HS256')
This is because jwt compares the expiration times to the utc time. You can double check your secret key is correct by using the jwt debug tool here: https://jwt.io/
More reading here: https://pyjwt.readthedocs.io/en/latest/usage.html#encoding-decoding-tokens-with-hs256
I also got stuck here and it was the %s that is platform specific that caused the bug. I changed is to %S (note capital)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With