M
M
Mikkkch2020-11-28 21:21:28
Python
Mikkkch, 2020-11-28 21:21:28

Does it make sense to check the presence of a user in the database when the secret key is unknown outside?

Hello, I have implemented an authentication system through cookies. Upon login, a token is generated for the user and stored with the key. When a user enters a page that should deny login to users who are not already logged in, you need to redirect or take some other action.
Here's what the code looks like:

authorization = False
cookie_key = request.cookies.get(self.cookie_key)

try:
    jwt.decode(cookie_key, self.secret, self.algorithm)
    authorization = True
except jwt.exceptions.DecodeError:
    pass

return authorization

Here, the decoding of the token lying in the session is carried out. If the token is incorrect, then the system immediately understands that the user is not logged in. Since a token can only be generated in code using a secret key, it is impossible to generate a "dummy" token with a name that does not exist in the database.

In the code of many other people, I have seen the following check:
payload = jwt.decode(cookie_key, self.secret, self.algorithm)
username = payload.get['sub']
user = db.get(username)
if not user:
     pass

Does it make sense?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2020-11-29
@Mikkkch

This makes sense in case:

  • The user was removed from the database after generating the token
  • Further in the code with user objects there will be work
  • The token generation service was hacked. Of course, such a check will not help much, but it may be a wake-up call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question