Understanding JWT: Basics of Authentication and Algorithms
Tags: webdev, jwt, authentication
Published: 2024-05-18 21:40:41

This is a JWT token. It consists of a Header, a Payload, and a Signature. JWTs are considered the best modern way of authentication.

`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`

They are stateless, meaning that you can authenticate users across many services, and they have multiple options for hashing.

Today we are going to discuss encryption algorithms and how a token works.

## Quick Overview

Before we take a deeper dive, we first need to understand how our application authenticates the user with JWT.

First, when we issue a JWT, we encrypt it with a SECRET KEY, which is basically a string. For example, `"thisismysecretkey"` or `"iUup54c5ZfbRk2VXbG3S7MTfTRk+9LkjG"`.

The key has to be a specific length. The secret key used in HS512 should be 64 bytes long. Why 64 bytes? Well, because 512 bits divided by 8 bits per byte equals 64 bytes.

So the token is basically an object, looks something like this.

```json
// header
{
  "alg": "HS512"
},
// payload
{
  "sub": "test@gmail.com",
  "iat": 1716051202,
  "exp": 1716057202
}
```

The `sub` is the email of the user, the `iat` is a timestamp of when the token was issued, and the `exp` is a timestamp of when the token expires. So, next time you send a token to an API, you need to know that it decrypts the token with that secret key and checks if the token is expired or not. The `alg` is what algorithm you are using.

## Algorithms

To choose from, there are a ton of algorithms like AES, RSA, and HS, and one of the most used is AES because of its quantum-resistant abilities. But not exactly, quantum computers might not exist right now, but in the future, they will come to life in the next 10 years.

And AES algorithms are both secure and not vulnerable to quantum attacks. That is because of some very complex stuff which I am not going to cover currently.

Now, for each algorithm, there are different sizes: HS256, HS512, etc. This is the length of the hash. The longer it is, the more difficult it is to decrypt. But don't change your algorithms too quickly because the more bytes a hash has, the slower it is to decrypt with your secret.

## Use Cases

The most common use case is JWT where HS512 or AES256. But here is a table with a detailed view of the most common algorithms.

| Algorithm | Type | Key Size | Security Level | Performance | Use Cases |
| --- | --- | --- | --- | --- | --- |
| AES | Symmetric Encryption | 128, 192, 256 bits | Very High | Fast | Data encryption, TLS/SSL, VPNs |
| SHA-256 | Hash Function | N/A (hash output size: 256 bits) | Very High | Fast | Data integrity, digital signatures |
| SHA-3 | Hash Function | N/A (hash output size: 224, 256, 384, 512 bits) | Very High | Moderate | Data integrity, digital signatures |
| RSA | Asymmetric Encryption | 1024, 2048, 4096 bits | High to Very High (depending on key size) | Moderate to Slow | Digital signatures, key exchange |
| ECDSA | Asymmetric Encryption | 224, 256, 384, 521 bits | Very High | Moderate | Digital signatures, cryptocurrency |
| HMAC | Message Authentication Code | Variable (depends on underlying hash function) | High | Fast | Data integrity, authentication |

## **Security Considerations**

When implementing JWT authentication, it's crucial to handle the secret key with care. The secret key should be stored on a secure place and never exposed to the client side.

Use a strong, randomly generated secret key to prevent brute-force attacks. Regularly rotate your keys and invalidate old tokens to enhance security.

To generate a secret key just use this command. Depending on how long you key should be change the last number. For a HS512 I am using 64

```plaintext
openssl rand -hex 64
```

## Refresh Token

Refresh tokens in JWT are used to obtain new access tokens without requiring the user to log in again.

When an access token expires, the client can use the refresh token to request a new one, ensuring continuous authentication. Refresh tokens are typically long-lived and stored securely, while access tokens have a shorter lifespan to minimize security risks. This approach enhances security by reducing the exposure of sensitive credentials and maintaining user sessions without frequent re-authentication.

## Final Words

In conclusion, understanding JWT authentication algorithms is essential for implementing secure and efficient authentication mechanisms in modern applications.

By choosing the appropriate algorithm and key size, you can ensure robust security while maintaining performance. Additionally, handling secret keys with care and utilizing refresh tokens can significantly enhance the security and user experience of your system.

Thanks for reading, and I hope you found this article helpful. If you have any questions, feel free to email me at [**kourouklis@pm.me**](mailto:kourouklis@pm.me)**, and I will respond.**

You can also keep up with my latest updates by checking out my X here: [**x.com/sotergreco**](http://x.com/sotergreco)