What to store in a JWT?

前端 未结 1 1274
生来不讨喜
生来不讨喜 2020-12-30 08:08

How do you guys deal with the same user on multiple devices? Won\'t data such as {admin: true} become stale except for the device that changed it?

Shoul

相关标签:
1条回答
  • 2020-12-30 08:26

    The JWT RFC stablish thre classes of claims:

    • Registered claims like sub, iss, exp or nbf

    • Public claims with public names or names registered by IANA which contain values that should be unique like email, address or phone_number. See full list

    • Private claims to use in your own context and values can collision

    None of these claims are mandatory

    A JWT is self-contained and should avoid use the server session providing the necessary data to perform the authentication (no need of server storage and database access). Therefore, role info can be included in JWT.

    When using several devices there are several reasons to revoke tokens before expiration, for example when user changes password, permissions or account deleted by admin. In this case you would need a blacklist or an alternative mechanism to reject the tokens

    A blacklist can include the token unique ID jti or simply set an entry (sub - iss) after updating critical data on user (password, persmissions, etc) and currentTime - maxExpiryTime < last iss. The entry can be discarded when currentTime - maxExpiryTime > last_modified (no more non-expired tokens sent).


    Registered Claims

    The following Claim Names are registered in the IANA "JSON Web Token Claims" registry established by Section 10.1.

    • iss (issuer): identifies the principal that issued the JWT.
    • sub (subject): identifies the principal that is the subject of the JWT. Must be unique
    • aud (audience): identifies the recipients that the JWT is intended for (array of strings/uri)
    • exp (expiration time): identifies the expiration time (UTC Unix) after which you must no longer accept this token. It should be after the issued-at time.
    • nbf(not before): identifies the UTC Unix time before which the JWT must not be accepted
    • iat (issued at): identifies the UTC Unix time at which the JWT was issued
    • jti (JWT ID): provides a unique identifier for the JWT.

    Example

    {
        "iss": "stackoverflow",
        "sub": "joe",
        "aud": ["all"],
        "iat": 1300819370,
        "exp": 1300819380,
        "jti": "3F2504E0-4F89-11D3-9A0C-0305E82C3301"
        "context": {
            "user": {
                "key": "joe",
                "displayName": "Joe Smith"
            },
            "roles":["admin","finaluser"]
        }
    }
    

    See alternatives here https://stackoverflow.com/a/37520125/6371459

    0 讨论(0)
提交回复
热议问题