Skip to content

[Feature]: Add JWT in /doc section #3893

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions docs/JWT/Advanced-topic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
---
id: advanced-jwt-topics
title: Advanced Topics
sidebar_label: Advanced Technique
sidebar_position: 6
tags: [JWT, web development, Security]
description: Advanced JWT Technique.
---

#### JWT in OAuth 2.0 and OpenID Connect

**How JWT is Used in These Protocols**:
:::note
- **OAuth 2.0**:
- **Access Tokens**: In OAuth 2.0, JWTs are often used as access tokens to grant access to resources. The token includes information about the scopes and permissions granted.
- **Bearer Tokens**: OAuth 2.0 can use JWTs as bearer tokens that are sent in HTTP headers to authenticate API requests.
:::

Example (OAuth 2.0 Access Token in HTTP Header):
```http
Authorization: Bearer <your.jwt.token>
```

- **OpenID Connect (OIDC)**:
- **ID Tokens**: OpenID Connect, an identity layer on top of OAuth 2.0, uses JWTs as ID tokens. These tokens provide information about the user and their authentication.
- **Claims**: The ID token contains claims about the user, such as their identity, and is used to establish a session in the client application.

Example (ID Token Claims):
```json
{
"iss": "https://issuer.com",
"sub": "user123",
"aud": "client_id",
"exp": 1618694400,
"iat": 1618690800,
"name": "John Doe",
"email": "[email protected]"
}
```


**Benefits of Using JWT in OAuth 2.0**:
- **Statelessness**: JWTs are self-contained, meaning they carry all necessary information in the token itself, which eliminates the need for server-side session storage.
- **Scalability**: Since JWTs are self-contained, they enable scalable distributed systems without the need for centralized session management.
- **Flexibility**: JWTs support various signing algorithms, allowing flexibility in terms of security and performance based on the use case.

#### Handling Large Payloads

**Compressing the Payload**:
- **Purpose**: Compressing the payload reduces the size of the JWT, which can be important for performance, especially when transmitting large amounts of data.
- **Techniques**:
- **Deflate**: Use compression algorithms such as gzip or deflate before encoding the payload.

Example (Compression in JavaScript):
```javascript
const pako = require('pako');

// Compress the payload
const compressedPayload = pako.deflate(JSON.stringify(payload), { to: 'string' });

// Encode and sign the compressed payload
const token = jwt.sign({ data: compressedPayload }, secret);
```

- **Considerations**: Ensure that both the issuer and the consumer of the token can handle the compression and decompression of the payload.

**Handling Large Claims Sets**:
- **Splitting Claims**: If the claims set is large, consider splitting the data into multiple tokens or using a combination of tokens and other storage mechanisms.
- **Using External References**: Store large data externally and include a reference or URL in the JWT. This approach reduces the token size and helps manage large claims effectively.

#### Custom Claims and Namespaces

**Defining and Using Custom Claims**:
- **Purpose**: Custom claims allow you to include additional data specific to your application’s needs.
- **How to Define**: Add custom claims to the payload when creating the JWT.

Example (Adding Custom Claims):
```javascript
const payload = {
sub: "user123",
role: "admin",
permissions: ["read", "write"]
};

const token = jwt.sign(payload, secret);
```

- **Best Practices**: Ensure that custom claims are used consistently and are well-documented.

**Namespacing to Avoid Conflicts**:
- **Purpose**: Namespacing helps avoid conflicts between custom claims and standard claims or between different applications.
- **How to Namespace**: Use a consistent naming convention for custom claims, such as prefixing with your application's domain.

Example (Namespaced Custom Claims):
```json
{
"sub": "user123",
"http://example.com/roles": ["admin"],
"http://example.com/permissions": ["read", "write"]
}
```


:::tip
1. **JWT in OAuth 2.0 and OpenID Connect**: JWTs are integral to these protocols, used for access and ID tokens, offering benefits like statelessness and scalability.
2. **Handling Large Payloads**: Compress payloads to reduce size and handle large claims by splitting data or using external references.
3. **Custom Claims and Namespaces**: Define custom claims to include specific application data and use namespacing to avoid conflicts with standard claims or between different applications.
:::
105 changes: 105 additions & 0 deletions docs/JWT/Components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
---
id: jwt-components
title: JWT Components
sidebar_label: Components
sidebar_position: 2
tags: [JWT, web development, Security]
description: JWT Components.
---

#### Header

**Structure and Format**:
The header of a JWT is a JSON object that contains two main pieces of information: the type of the token and the signing algorithm being used.

**Common Fields**:
- **alg**: Specifies the algorithm used to sign the token, such as HMAC SHA256 (HS256) or RSA (RS256).
- **typ**: Specifies the type of the token, which is usually set to "JWT".

Example Header:
```json
{
"alg": "HS256",
"typ": "JWT"
}
```
This JSON object is then base64Url encoded to form the first part of the JWT.

#### Payload

The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims:

**Registered Claims**:
These are a set of predefined claims which are not mandatory but recommended to provide a set of useful, interoperable claims:
:::important
- **iss (issuer)**: Identifies the principal that issued the JWT.
- **sub (subject)**: Identifies the principal that is the subject of the JWT.
- **aud (audience)**: Identifies the recipients that the JWT is intended for.
- **exp (expiration time)**: Identifies the expiration time on or after which the JWT must not be accepted for processing.
- **nbf (not before)**: Identifies the time before which the JWT must not be accepted for processing.
- **iat (issued at)**: Identifies the time at which the JWT was issued.
- **jti (JWT ID)**: Provides a unique identifier for the JWT.
:::

Example Payload with Registered Claims:
```json
{
"iss": "example.com",
"sub": "user123",
"aud": "example.com",
"exp": 1618704000,
"nbf": 1618700400,
"iat": 1618700400,
"jti": "unique-id-123"
}
```

**Public Claims**:
These claims can be defined at will by those using JWTs but should be defined in the IANA JSON Web Token Registry to avoid collisions.

Example Public Claims:
```json
{
"role": "admin",
"username": "johndoe"
}
```

**Private Claims**:
These are custom claims created to share information between parties that agree on using them. These claims are not registered or public, thus avoiding collisions in usage.

Example Private Claims:
```json
{
"customClaim": "customValue"
}
```

This JSON object is then base64Url encoded to form the second part of the JWT.

#### Signature

**How It's Created**:
To create the signature part, you have to take the encoded header, the encoded payload, a secret key, and the algorithm specified in the header, and sign that.

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

**Purpose and Importance**:
The signature is used to verify that the sender of the JWT is who it says it is (authentication) and to ensure that the message wasn't changed along the way (integrity). When the recipient receives the token, they can decode the header and payload, but they must verify the signature using the secret key to ensure that the token is valid and has not been tampered with.

Example JWT Signature:
```json
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
```

90 changes: 90 additions & 0 deletions docs/JWT/Introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
---
id: jwt-turorial
title: What is JWT?
sidebar_label: Introduction
sidebar_position: 1
tags: [JWT, web development, Security]
description: JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object.
---

**Definition and Purpose**:
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with HMAC algorithm) or a public/private key pair using RSA or ECDSA.

**Typical Use Cases**:
- **Authentication**: After a user logs in, the server generates a JWT and sends it to the client. The client then sends this token in subsequent requests, allowing the server to verify the user's identity.
- **Information Exchange**: JWTs can securely transmit information between parties because they can be signed, ensuring the data's integrity and authenticity.

#### JWT Structure

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

1. **Header**
2. **Payload**
3. **Signature**

Each part is base64Url encoded and concatenated with dots.

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

:::important
Example:
```json
{
"alg": "HS256",
"typ": "JWT"
}
```
:::

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

:::important
**Payload**:
The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims:
- **Registered Claims**: These are predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some examples are `iss` (issuer), `exp` (expiration time), `sub` (subject), and `aud` (audience).
- **Public Claims**: These can be defined at will by those using JWTs but should be defined in the IANA JSON Web Token Registry to avoid collisions.
- **Private Claims**: These are custom claims created to share information between parties that agree on using them.
:::
Example:
```json
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
```

This JSON is then 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, and 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.

**Putting It All Together**:
The output is three Base64Url strings separated by dots that can be easily passed in HTML and HTTP environments:
```
xxxxx.yyyyy.zzzzz
```

### Example JWT:
A JWT might look like this:
```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```
:::note
- The first part (before the first dot) is the encoded header.
- The second part is the encoded payload.
- The third part is the signature.
:::

8 changes: 8 additions & 0 deletions docs/JWT/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "JWT",
"position": 25,
"link": {
"type": "generated-index",
"description": "JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. It is commonly used for authentication and information exchange. "
}
}
Loading
Loading