skip to Main Content

I have an API built with Flask and using Gunicorn with postgreSQL as database on linux (centOS)

When setting multiple workers using Gunicorn, if a user log to the API and get a token, the token won’t be correct if he uses it to perform a request.

It works when there is only one worker and multiple threads but not with multiple workers. How should I handle the storage of the tokens so the different workers can retrieve the token from a unique source of data?

To generate the token we retrieve the secret key and create a json web token. Then we store this token and the username in a dictionary.

Also, the secret key is generated at each start of flask, maybe using the preload_app of gunicorn can help to have the same secret key on each worker.

2

Answers


  1. Besides connecting your http requests to their respective functions in python source code, Gunicorn, has very little to do with authentication.

    Your authentication tokens would most likely be saved in the database and subsequently retrieved / matched for every request. You may choose to cache it if need be.

    Login or Signup to reply.
  2. The idea behind JWT is that the token is returned to the user, which then attaches it to every request. Then you don’t have to store anything, because the token has a built in content hash that is invalid whenever someone messes with the token contents. The only thing you could want to do when issuing the token is to log which user has logged in at which point.

    In addition, I like to store my secret keys as ENV variables, which all threads/workers can access. You can of course have a preload step in your deployment to regenerate it, but keep that out of the lifecycle of your Flask application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search