Is it ok to store user credentials in the JWT

后端 未结 3 2031
囚心锁ツ
囚心锁ツ 2020-12-31 08:52

Is it ok to store user credentials (username / password) in the JWT (so sign it and verify the resulted token later)?

I heard that

3条回答
  •  余生分开走
    2020-12-31 09:21

    Shortly: yes, it is OK to pass/receive sensitive data in JWT if you encrypt the data before placing into JWT's payload and decrypt it after the JWT validation to use it.

    1. In a general case you would not need to keep user credentials in the JWT because the JWT is by itself a dinamically generated credential that represents the login / password provided at the JWT's generation time.

      1.1 You could however pass something that is not as sensitive as pure login / password but still bears the valuable information you need at the JWT validation time. It can be user ID (in a sub claim, hashed if desired), or access level code or the like.

    2. Nevertheless if you wish you can pass the sensitive information with JWT. And this is all pretty easy as per below.

      2.1 For sensitive data you could use your specific private claims in the JWT's payload, e.g.:

      {
        // These are registered claims: (see https://tools.ietf.org/html/rfc7519#section-4.1)
        "sub": "1234567890",
        "name": "John Doe",
        "iat": 1516239022
      
        // There can be some public claims you are not afraid to expose to the world
        // these are omitted here for brevity (see https://tools.ietf.org/html/rfc7519#section-4.2).
        "omitted": "for brevity",
      
        // And here can go some private claims you wish to include in the payload, e.g.:
        "sensitiveInfo": {
          "username": "admin",
          "password": "12345",
          "account_balance": 10000,
          "etc": "something else"
        }
      }
      

      2.2 The sensitiveInfo payload key by default is only base64-encoded (so it is easily read by anyone who gets the JWT). To make it secure you can encrypt it with some external module (e.g. crypto or bcrypt on NodeJS or PHP's techniques of your choice).

      2.3 In this case:

      • At the JWT generation step you have to encrypt the key's data before you provide the entire payload to JWT generator.
      • At the JWT validation step, after the JWT successfully passes the standard validation (e.g. jsonwebtocken jwt.verify() in Node) you get the decoded payload with encrypted data in sensitiveInfo key. You now just have to decrypt the data and use it as you planned.

    This is it.

提交回复
热议问题