J
J
Jekson2021-04-28 10:51:32
JSON Web Token
Jekson, 2021-04-28 10:51:32

How to bind the right user to the right session?

Help me understand how JWT-based user sessions work. Now I have implemented the following functionality:
when the user authorizes, a JWT is created which is written to redis in this form

{
'session' : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw
}

The token contains the necessary info on the user - id, email, permission_type

Now, as I understand it, each request where an authorization check should be performed should check whether the user has a session or redirect to the log_in page.
The code is in python, but I think the meaning is clear
async def get_current_user():
    try:
        session = await redis_cache.get('session')
        payload = jwt.decode(
            session,
            config('JWT_SECRET'),
            algorithms=config('JWT_ALGORITHM'),
        )
        return payload['user']
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authentication"
        )

My question is:
how to match a user with a token in radish, here is this query
session = await redis_cache.get('session')
how to understand which key to pass in the get(' session ') request
And which key to use when generating a token entry in the database.
That is, now I have a hardcode for one user, there is a session key in the database and I pass it in the request. But what logic should be with a large number of users?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-04-28
@Lepilov

JWT is used in stateless modes. The main token is not stored on the server at all. It is signed by the issuing server, and if the signature is correct, then the production server simply trusts the information in the token.
If the client did not send a token or sent an expired token or the signature is incorrect, then the server requires authorization in response. If a valid token arrives, then the server simply uses the data from the token.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question