Home >Web Front-end >JS Tutorial >Understanding the JWT

Understanding the JWT

王林
王林Original
2024-08-08 13:46:24725browse

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.

Understanding the JWT

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

  1. Security - JWTs are digitally signed, ensuring the integrity and authenticity of the data
  2. Compact - JWTs are small in size, making them efficient to transmit over the network.
  3. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn