What Is JWT?
JWT stands for json web token, it’s open stander use to transmit information between parties as a JSON object. It is compact, URL-safe, and used extensively in web applications for authentication and information exchange.
JWTs are digitally signed using keys and secrets. We verify the JWT with these keys and the signature to authenticate the user. Most web systems use JWTs to authorize users to access certain resources.
Token Components
A JWT has three main components: the header, the payload, and the signature. When we create a token, we pass the header and payload, and then the token generates the signature.
Headre - The header of a JWT contains metadata about the token. It includes three values: alg, typ, and kid. The alg specifies the algorithm used to sign the token, typ indicates the token type, and kid is an optional parameter used to identify the key. Whether to include kid depends on your use case.
{ "alg": "RS256", // allow [HS256,RS256,ES256] "typ": "JWT", // Specific Type Of token "kid": "12345" // Used to indicate which key was used to sign the JWT. This is particularly useful when multiple keys are in use }
Payload - In Payload we specify some custom data mostly add user specific data into payload like user id and role.
{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
Signature - The signature is generated by encoding the header and payload with a secret key (for HS256) or signing them with a private key (for RSA), and then hashing the result. This signature is used to verify the token.
How Token Is Created
As we discussed, a JWT has three components: the header, the payload, and the signature. We provide the header and payload, and the signature is generated from them. After combining all these components, we create the token.
// Header Encoding Base64Url Encode({ "alg": "RS256", "typ": "JWT" }) → eyJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9 // Payload Encoding Base64Url Encode({ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }) → eyJzdWIiOiAiMTIzNDU2Nzg5MCIsICJuYW1lIjogIkpvaG4gRG9lIiwgImlhdCI6IDE1MTYyMzkwMjJ9 // Concatenate Encoded header and payload ConcatenatedHash = Base64Url Encode(Header) + "." + Base64Url Encode(Payload) //Create Signature Hash = SHA-256(ConcatenatedHash) Signature = RSA Sign(Hash with Private Key) or HS256 Sign(Hash with secrate) // Create Token Token = Base64UrlEncode(Header) +"."+ Base64UrlEncode(Payload) +"."+ Signature
So, the process to create a JWT is as follows: we encode the payload and headers, then generate the signature from them.
Verifying JWT Tokens
Earlier, we discussed how to create a JWT. Now, let's discuss how to verify a JWT. The verification process is essentially the reverse of token creation. First, we decrypt the token using a secret or public key. Then, we concatenate the header and payload to generate a signature. If the generated hash matches the signature, the token is valid; otherwise, it is not valid.
// Token we recive in this formate Token = Base64UrlEncode(Header) +"."+ Base64UrlEncode(Payload) +"."+ Signature // Decrypt Signature TokenHash = RSA Decrypt(Hash with Public Key) or HS256 Sign(Hash with secrate) // Generate Hash From Encoded Header and Payload Hash = SHA-256(Base64UrlEncode(Header) +"."+ Base64UrlEncode(Payload)) // Compare Hash if(TokenHash == Hash) "Valid" else "Not Valid"
Benefits of Using JWT
- Security - JWTs are digitally signed, ensuring the integrity and authenticity of the data
- Compact - JWTs are small in size, making them efficient to transmit over the network.
- Self-Contained - JWTs contain all the necessary information about the user, reducing the need to query the database multiple times.
JWT provides all the above benefits, making it a popular choice for most authentication mechanisms to authorize users. Additionally, JWT can be used with various authentication techniques, such as DPoP and others.
How to Use JWT in Your Code
To use JWT in code, we utilize the jsonwebtoken npm package. There are two methods for working with JWTs: the straightforward method using a secret key and the key pair method (using public and private keys).
Using Secret
import jwt from 'jsonwebtoken'; // Define the type for the payload interface Payload { userId: number; username: string; } // Secret key for signing the JWT const secretKey: string = 'your-very-secure-secret'; // Payload to be included in the JWT const payload: Payload = { userId: 123, username: 'exampleUser' }; // Sign the JWT const token: string = jwt.sign(payload, secretKey, { expiresIn: '1h' }); console.log('Generated Token:', token);
import jwt from 'jsonwebtoken'; // Secret key for signing the JWT const secretKey: string = 'your-very-secure-secret'; // Verify the JWT try { const decoded = jwt.verify(token, secretKey) as Payload; console.log('Decoded Payload:', decoded); } catch (err) { console.error('Token verification failed:', (err as Error).message); }
Using KeyPair Method
import * as jwt from 'jsonwebtoken'; import { readFileSync } from 'fs'; // Load your RSA private key const privateKey = readFileSync('private_key.pem', 'utf8'); // Define your payload const payload = { sub: '1234567890', name: 'John Doe', iat: Math.floor(Date.now() / 1000) // Issued at }; // Define JWT sign options const signOptions: jwt.SignOptions = { algorithm: 'RS256', expiresIn: '1h' // Token expiration time }; // Generate the JWT const token = jwt.sign(payload, privateKey, signOptions); console.log('Generated JWT:', token);
import * as jwt from 'jsonwebtoken'; import { readFileSync } from 'fs'; // Load your RSA public key const publicKey = readFileSync('public_key.pem', 'utf8'); // Define JWT verify options const verifyOptions: jwt.VerifyOptions = { algorithms: ['RS256'] // Specify the algorithm used }; try { // Verify the JWT const decoded = jwt.verify(token, publicKey, verifyOptions) as jwt.JwtPayload; console.log('Decoded Payload:', decoded); } catch (error) { console.error('Error verifying token:', error); }
Conclusion
In summary, JSON Web Tokens (JWTs) securely transmit information between parties using a compact format. RSA signing and verification involve using a private key for signing and a public key for verification. The TypeScript examples illustrate generating a JWT with a private RSA key and verifying it with a public RSA key, ensuring secure token-based authentication and data integrity.
The above is the detailed content of Understanding the JWT. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
