JWT Token Implementation and Metodology

Erdem Erbaba
4 min readJul 5, 2024

--

JSON Web Tokens (JWT) are 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, which 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.

1. Introduction to JWT
— Definition
— Use Cases

2. Structure of JWT
— Header
— Payload
— Signature

3. JWT Creation Process
— Step-by-step process
— Libraries and tools

4. JWT Implementation in a Web Application
— Generating JWT
— Verifying JWT
— Middleware Integration

5. Security Considerations
— Common vulnerabilities
— Best practices

6. Conclusion
— Summary of key points

### Introduction to JWT

JSON Web Tokens (JWT) are 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, which 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.

#### Use Cases

JWTs are commonly used in scenarios such as:

- Authentication: Once the user logs 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 can also be used to securely transmit information between parties because they can be signed, which ensures that the claims cannot be altered.

### Structure of JWT

A JSON Web Token is composed of three parts, separated by dots (.): Header, Payload, and Signature. Therefore, a JWT typically looks like the following: `xxxxx.yyyyy.zzzzz`.

#### Header

The header typically consists of two parts: the type of token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.

Example Header:
```json
{
“alg”: “HS256”,
“typ”: “JWT”
}
```

This JSON is Base64Url encoded to form the first part of the JWT.

#### Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: registered, public, and private claims.

Example Payload:
```json
{
“sub”: “1234567890”,
“name”: “John Doe”,
“admin”: true
}
```

This is also Base64Url encoded to form the second part of the JWT.

#### Signature

To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
```
HMACSHA256(
base64UrlEncode(header) + “.” +
base64UrlEncode(payload),
secret)
```

The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.

### JWT Creation Process

Creating a JWT involves several steps, typically handled by a library in your programming language of choice. Here, we’ll use Python with the PyJWT library as an example.

1. **Install PyJWT Library**
```bash
pip install PyJWT
```

2. **Generate a JWT**

```python
import jwt
import datetime

def create_jwt(secret_key):
payload = {
‘sub’: ‘1234567890’,
‘name’: ‘John Doe’,
‘admin’: True,
‘iat’: datetime.datetime.utcnow(),
‘exp’: datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)
}
token = jwt.encode(payload, secret_key, algorithm=’HS256')
return token
```

3. **Verify a JWT**

```python
def verify_jwt(token, secret_key):
try:
payload = jwt.decode(token, secret_key, algorithms=[‘HS256’])
return payload
except jwt.ExpiredSignatureError:
return ‘Signature has expired’
except jwt.InvalidTokenError:
return ‘Invalid token’
```

### JWT Implementation in a Web Application

#### Generating JWT

When a user logs in, the server will generate a JWT and send it back to the client. The client will then include this token in the Authorization header of every subsequent request.

```python
from flask import Flask, request, jsonify

app = Flask(__name__)
SECRET_KEY = ‘your-256-bit-secret’

@app.route(‘/login’, methods=[‘POST’])
def login():
# Normally, you’d verify the username and password here.
username = request.json.get(‘username’)
password = request.json.get(‘password’)

if username == ‘user’ and password == ‘password’:
token = create_jwt(SECRET_KEY)
return jsonify({‘token’: token})
else:
return jsonify({‘message’: ‘Invalid credentials’}), 401
```

#### Verifying JWT

To protect routes, you can create a middleware to verify the JWT.

```python
from functools import wraps

def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get(‘Authorization’)

if not token:
return jsonify({‘message’: ‘Token is missing!’}), 403

try:
data = verify_jwt(token, SECRET_KEY)
except:
return jsonify({‘message’: ‘Token is invalid!’}), 403

return f(*args, **kwargs)

return decorated

@app.route(‘/protected’, methods=[‘GET’])
@token_required
def protected():
return jsonify({‘message’: ‘This is only available for people with valid tokens.’})
```

### Security Considerations

#### Common Vulnerabilities

1. **Token Expiry**: Always set an expiration date on your tokens. This limits the damage in case a token is compromised.
2. **Secret Management**: Keep your signing keys secret and rotate them periodically.
3. **Algorithm Confusion**: Ensure your server verifies that the algorithm specified in the header matches what you expect.

#### Best Practices

1. **Use Strong Secrets**: Use sufficiently long and random secrets for HMAC signing.
2. **Validate Inputs**: Validate all inputs and ensure that they are correctly parsed and handled.
3. **Use HTTPS**: Always use HTTPS to protect tokens in transit.

### Conclusion

JWTs provide a powerful and flexible way to handle authentication and information exchange in web applications. By understanding their structure, creation process, and security considerations, developers can implement JWTs effectively and securely. Remember to use robust libraries and follow best practices to ensure the security of your tokens.

--

--