JWT JSON Web Tokens
1. What are JWTs?JSON Web Tokens (JWTs) are an open - standard (RFC 7519) method for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.2. Structure of a JWTA JWT typically consists of three parts, separated by dots (.), namely:HeaderThe header usually consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA. For example:TypeScript取消自动换行复制{"alg": "HS256","typ": "JWT"}This JSON object is then base64Url encoded to form the first part of the JWT.PayloadThe payload is where the claims are stored. Claims are statements about an entity (usually the user) and additional data. There are three types of claims: registered claims, public claims, and private claims.
Registered claims: These are a set of predefined claims which are not mandatory but recommended, such as iss (issuer), exp (expiration time), sub (subject), etc.
Public claims: These can be defined at will by those using JWTs as long as they are unique to avoid collisions.
Private claims: These are custom claims created for sharing information between parties that agree on using them.
For example:TypeScript取消自动换行复制{"sub": "1234567890","name": "John Doe","iat": 1516239022}This JSON object is base64Url encoded to form the second part of the JWT.SignatureTo create the signature part, you need the encoded header, the encoded payload, a secret, and the hashing algorithm specified in the header. For example, if you are using HMAC SHA256, the signature will be created as follows:TypeScript取消自动换行复制HMACSHA256(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)The signature is used to verify that the message wasn't changed along the way, and, in the case of tokens signed with a public/private key pair, it can also verify the identity of the JWT's issuer.3. How JWTs Work
Issuance: When a user logs in to an application, the application verifies the user's credentials. If the credentials are correct, the application creates a JWT. The JWT contains information about the user, such as user ID, username, and any relevant permissions. The application then signs the JWT using a secret key (for symmetric algorithms) or its private key (for asymmetric algorithms) and sends the token back to the user.
Usage: The user then includes the JWT in the authorization header of subsequent requests to the application's protected routes. The format is usually Bearer <token>. For example:
TypeScript取消自动换行复制Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.7QfP9Y7e - hXy70Z99a559d19c4777a9c7d8d9e8d87c89c
Verification: When the application receives a request with a JWT in the authorization header, it extracts the token. It then verifies the signature of the JWT using the corresponding secret key (symmetric) or public key (asymmetric). If the signature is valid, the application can trust the information in the JWT. It can then extract the user information from the payload and use it to authorize the user's request.
4. Use Cases of JWTsAuthenticationJWTs are commonly used for authentication in single - page applications (SPAs), mobile applications, and microservices architectures. Instead of relying on traditional session - based authentication, which requires maintaining session state on the server, JWTs are self - contained and stateless. The server can verify the JWT on each request without referring to any server - side session data.AuthorizationThe information in the JWT payload can be used to determine what actions a user is authorized to perform. For example, if the payload contains user roles or permissions, the application can check these claims to allow or deny access to certain resources or endpoints.Information ExchangeJWTs can be used to securely transfer information between different systems. Since they are signed, the receiving system can trust that the information has not been tampered with. For example, in a distributed system, one service can send a JWT to another service to pass along user - related information or other relevant data.5. Security Considerations
Key Management: The security of JWTs heavily depends on the secrecy of the signing key. For symmetric algorithms, the secret key must be kept secret and not disclosed. For asymmetric algorithms, the private key must be safeguarded. If the key is compromised, an attacker can create or modify JWTs at will.
Token Expiration: Setting an appropriate expiration time (exp claim) for JWTs is crucial. If tokens have a long lifespan, there is a higher risk of them being compromised. On the other hand, if the expiration time is too short, it may cause inconvenience to users as they may need to re - authenticate frequently.
Token Storage: JWTs should be stored securely on the client - side. In web applications, storing JWTs in local storage is not recommended as it can be accessed by malicious JavaScript code running on the page. Instead, techniques like using HTTP - only cookies (if applicable) or storing the token in a more secure location in mobile applications should be considered.
In conclusion, JSON Web Tokens provide a flexible, secure, and widely - adopted way to handle authentication, authorization, and information exchange in modern web and mobile applications. Understanding how they work and the associated security considerations is essential for building secure and reliable systems.
Last updated