Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

JWT Tokens Tutorial

Introduction to JWT

JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

Structure of JWT

A JWT is composed of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following:

xxxxx.yyyyy.zzzzz

Creating a JWT

Creating a JWT involves specifying the header and payload, then signing the JWT with a secret key. Here’s an example in JavaScript using the jsonwebtoken library:

npm install jsonwebtoken
const jwt = require('jsonwebtoken');

const payload = {
    username: 'exampleUser',
    role: 'admin'
};

const secretKey = 'your-256-bit-secret';

const token = jwt.sign(payload, secretKey, { algorithm: 'HS256' });

console.log(token);
                

Verifying a JWT

To verify a JWT, you need to use the same secret key that was used to sign the JWT. Here’s how you can do it:

const token = 'your.jwt.token';

jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
        console.log('Token is invalid:', err);
    } else {
        console.log('Token is valid:', decoded);
    }
});
                

Example Use Cases

JWTs are commonly used for:

  • Authorization: Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
  • Information Exchange: JWTs are a good way of securely transmitting information between parties. Because JWTs can be signed, you can be sure the senders are who they say they are.

Security Considerations

While JWTs are stateless and do not need to be stored in a database, there are several security considerations to keep in mind:

  • Always use HTTPS to ensure that the secret key and the JWT are transmitted securely.
  • Use strong secret keys and keep them confidential.
  • Set appropriate expiration times for JWTs to limit the time window in which they can be used.
  • Be aware of JWT vulnerabilities such as token tampering and replay attacks.