Understanding the JWT
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
