In practical applications, JWT (JSON Web Tokens) is commonly used for authentication and information exchange. JWT typically consists of three parts: Header, Payload, and Signature. To retrieve userId from a JWT, the primary steps involve parsing and reading its Payload section.
Steps:
-
Obtain JWT Token: First, retrieve the JWT from the client request. Typically, JWT is sent in the HTTP header under the Authorization field.
plaintextAuthorization: Bearer <token> -
Split Token: JWT is composed of three segments separated by dots (.), namely Header, Payload, and Signature. Split the string at each dot to access these segments individually.
pythonheader, payload, signature = token.split('.') -
Decode Payload: The Header and Payload of JWT are typically Base64Url encoded. To access the data in the Payload, decode it.
pythonimport base64 def base64_url_decode(inp): rem = len(inp) % 4 if rem > 0: inp += '=' * (4 - rem) return base64.urlsafe_b64decode(inp) decoded_payload = base64_url_decode(payload) -
Parse Payload: The decoded Payload is a JSON string. Parse this string into an object to access the data.
pythonimport json payload_data = json.loads(decoded_payload) -
Retrieve userId: Typically, userId is included in the Payload. The exact key depends on how the JWT was generated. Common keys include
user_id,userId, andsub(representing subject).pythonuser_id = payload_data.get('userId') or payload_data.get('user_id') or payload_data.get('sub')
Example:
If you have a JWT like the following:
plaintexteyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMzQ1NiwibmFtZSI6IkphbmUgRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
After decoding and parsing as per the above steps, you can extract userId from the Payload.