0

I have created a JWT Token based login system, I am able to generate the token and I have added the expiry time to that token.

Requiremenent:

  • When the user is accessing the UI the token should not expire.

  • When the User is not Accessing the UI for 10 minutes the token should expire.

I am using Angular for UI and python flask for backend, I don't no from where(either UI or Backend) I have to handle this. I am thinking we have to handle it from python flask so I have used python and flask tags, If I am wrong let me know.

my backend code:

def loginM(email, password):
     try:
       time_count = get_time_count_details()
       user = Credentials.query.filter_by(email=email).first()
       user_reg = Registration.query.filter_by(email=email).first()
       if bcrypt.check_password_hash(user.password, password):
           payload = {"email": user.email, 'user_id': user.user_id,
                      'first_name': user_reg.first_name,
                      'company': user_reg.company, 'mobile_num': user_reg.mobile_number,
                      'exp': time.time() + time_count}
        secret_key = open(SECRET_KEY).read()
        token = jwt.encode(payload, secret_key, algorithm='RS256').decode('utf-8')
        return dict(token=token)
    else:
        return dict(Unsucessful="Invalid Email Address and password")
except Exception:
    return False

1 Answers1

-1

you can use redis key expire instead of exp in jwt payload

  • jwt payload dont save exp value, jwt will not expired. payload like this:
payload = {"email": user.email, 'eco_user_id': user.eco_user_id,
           'first_name': user_reg.first_name,
           'company': user_reg.company, 'mobile_num': user_reg.mobile_number,}
  • redis save token,and set expiration as 10min
redis.set(token, user.id)
redis.expire(token, 60 * 10)

When the user is accessing the api, sever will find token in redis.if find token in redis,we will refresh redis expiration time,otherwise return 403 and tell user to login

baskershu
  • 109
  • 6
  • what is this " user.id " – suresh kumar Apr 22 '20 at 08:04
  • user.id is the key what you use to get the user instance. it maybe `email` or `mobile_number` – baskershu Apr 22 '20 at 08:16
  • If going this route you might as well just use session as they are already well designed and tested for these cases. For extending JWTs you might want to take a look at this answer: https://stackoverflow.com/a/46284627 – vimalloc Apr 22 '20 at 20:38