diff --git a/docs/JWT/Advanced-topic.md b/docs/JWT/Advanced-topic.md new file mode 100644 index 000000000..51f3fca98 --- /dev/null +++ b/docs/JWT/Advanced-topic.md @@ -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 + ``` + +- **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": "john.doe@example.com" + } + ``` + + +**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. +::: \ No newline at end of file diff --git a/docs/JWT/Components.md b/docs/JWT/Components.md new file mode 100644 index 000000000..fa3979f4a --- /dev/null +++ b/docs/JWT/Components.md @@ -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 +) +``` + \ No newline at end of file diff --git a/docs/JWT/Introduction.md b/docs/JWT/Introduction.md new file mode 100644 index 000000000..29e38d5bb --- /dev/null +++ b/docs/JWT/Introduction.md @@ -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. +::: + \ No newline at end of file diff --git a/docs/JWT/_category_.json b/docs/JWT/_category_.json new file mode 100644 index 000000000..aa9f8e3d3 --- /dev/null +++ b/docs/JWT/_category_.json @@ -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. " + } +} \ No newline at end of file diff --git a/docs/JWT/creating-and-verfy.md b/docs/JWT/creating-and-verfy.md new file mode 100644 index 000000000..8e6b23002 --- /dev/null +++ b/docs/JWT/creating-and-verfy.md @@ -0,0 +1,120 @@ +--- +id: jwt-creating-verifying +title: Creating and Verifying JWTs +sidebar_label: Creating and Verifying +sidebar_position: 3 +tags: [JWT, web development, Security] +description: Creating and Verifying JWTs. +--- + +#### Creating JWTs + +**Steps to Create a JWT**: +1. **Define the Header**: + - The header typically consists of two parts: the type of the token (which is JWT) and the signing algorithm being used (e.g., HMAC SHA256 or RSA). + +2. **Define the Payload**: + - The payload contains the claims. These claims can be registered claims (like `iss`, `exp`, etc.), public claims, or private claims. + +3. **Encode the Header and Payload**: + - Both the header and the payload are JSON objects that need to be base64Url encoded. + +4. **Create the Signature**: + - The signature is created by taking the encoded header and payload, a secret key (or private key if using RSA/ECDSA), and the algorithm specified in the header to sign that data. + +5. **Combine All Parts**: + - The final JWT is formed by concatenating the base64Url encoded header, payload, and signature with dots (`.`) in between. + +**Encoding the Header and Payload**: +- Header (JSON): + ```json + { + "alg": "HS256", + "typ": "JWT" + } + ``` +- Payload (JSON): + ```json + { + "sub": "1234567890", + "name": "John Doe", + "admin": true, + "iat": 1516239022 + } + ``` + +- Base64Url encoding of header: + ``` + eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 + ``` +- Base64Url encoding of payload: + ``` + eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0 + ``` + +**Signing the Token**: +- Create the signature by combining the encoded header, payload, and a secret key using the algorithm specified (e.g., HMAC SHA256): + ```javascript + HMACSHA256( + base64UrlEncode(header) + "." + + base64UrlEncode(payload), + secret + ) + ``` +- Example signature: + ``` + SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c + ``` + +**Final JWT**: +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +#### Verifying JWTs + +**Steps to Verify a JWT**: +1. **Extract the Components**: + - Split the JWT into its three parts: header, payload, and signature. + +2. **Decode the Header and Payload**: + - Base64Url decode the header and payload to get the original JSON objects. + +3. **Validate the Signature**: + - Recreate the signature using the same method as when the JWT was created, using the header and payload, and compare it with the received signature. + +4. **Check the Claims**: + - Verify the claims in the payload, such as `exp` (expiration time), `nbf` (not before), and `iat` (issued at). + +**Validating the Signature**: +- Recreate the signature using the received encoded header and payload and the secret key: + ```javascript + const validSignature = HMACSHA256( + base64UrlEncode(header) + "." + + base64UrlEncode(payload), + secret + ); + if (validSignature !== receivedSignature) { + throw new Error('Invalid signature'); + } + ``` + +**Checking the Claims**: +- Check the expiration time (`exp`): + ```javascript + const currentTime = Math.floor(Date.now() / 1000); + if (payload.exp && currentTime > payload.exp) { + throw new Error('Token expired'); + } + ``` + +- Check the not before (`nbf`) and issued at (`iat`) claims: + ```javascript + if (payload.nbf && currentTime < payload.nbf) { + throw new Error('Token not active yet'); + } + if (payload.iat && currentTime < payload.iat) { + throw new Error('Token issued in the future'); + } + ``` + \ No newline at end of file diff --git a/docs/JWT/implement.md b/docs/JWT/implement.md new file mode 100644 index 000000000..07b60b9c7 --- /dev/null +++ b/docs/JWT/implement.md @@ -0,0 +1,406 @@ +--- +id: jwt-implement +title: Implementing JWT +sidebar_label: Implementation +sidebar_position: 4 +tags: [JWT, web development, Security] +description: Implementing of the project in JWT. +--- + +#### Server-Side Implementation + +**Libraries and Tools**: +- **Node.js**: `jsonwebtoken` library +- **Python**: `PyJWT` library +- **Java**: `jjwt` library +- **Ruby**: `jwt` gem + +**Example Code Snippets** + + + +**Creating a Token (Node.js using `jsonwebtoken`)**: +1. **Install the library**: + ```bash + npm install jsonwebtoken + ``` + +2. **Code to create a token**: + ```javascript + const jwt = require('jsonwebtoken'); + + const payload = { + sub: "1234567890", + name: "John Doe", + admin: true + }; + + const secret = "your-256-bit-secret"; + + const token = jwt.sign(payload, secret, { expiresIn: '1h' }); + + console.log(token); + ``` + +**Verifying a Token (Node.js using `jsonwebtoken`)**: +1. **Code to verify a token**: + ```javascript + const jwt = require('jsonwebtoken'); + + const token = "your.jwt.token.here"; + const secret = "your-256-bit-secret"; + + try { + const decoded = jwt.verify(token, secret); + console.log(decoded); + } catch (err) { + console.error('Token verification failed:', err); + } + ``` + + +### Installation + +First, you need to install the PyJWT library if you haven't already: + +```bash +pip install pyjwt +``` + +### Creating (Encoding) a Token + +To create a JWT, you need a payload (data) and a secret key. The payload typically contains claims about the user and any additional metadata. + +```python +import jwt +import datetime + +# Define the payload +payload = { + 'user_id': 123, + 'username': 'example_user', + 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) # Token expiration time +} + +# Define the secret key +secret_key = 'your_secret_key' + +# Create the token +token = jwt.encode(payload, secret_key, algorithm='HS256') + +print(f"Generated Token: {token}") +``` + +### Verifying (Decoding) a Token + +To verify a JWT, you need the token and the same secret key that was used to create the token. If the token is valid and has not expired, you can decode it to retrieve the payload. + +```python +# Define the token you received +received_token = token + +# Decode the token +try: + decoded_payload = jwt.decode(received_token, secret_key, algorithms=['HS256']) + print(f"Decoded Payload: {decoded_payload}") +except jwt.ExpiredSignatureError: + print("Token has expired") +except jwt.InvalidTokenError: + print("Invalid token") +``` + + + + +### Setup + +First, add the `jjwt` library to your project. If you're using Maven, add the following dependency to your `pom.xml`: + +```xml + + io.jsonwebtoken + jjwt + 0.9.1 + +``` + +If you're using Gradle, add the following to your `build.gradle`: + +```groovy +implementation 'io.jsonwebtoken:jjwt:0.9.1' // Check for the latest version +``` + +### Creating (Encoding) a Token + +Here’s how to create a JWT using `jjwt`: + +```java +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import java.util.Date; + +public class JwtExample { + + private static final String SECRET_KEY = "your_secret_key"; + + public static String createToken(String userId, String username) { + return Jwts.builder() + .setSubject(userId) + .claim("username", username) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) // 30 minutes expiration + .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes()) + .compact(); + } + + public static void main(String[] args) { + String token = createToken("123", "example_user"); + System.out.println("Generated Token: " + token); + } +} +``` + +### Verifying (Decoding) a Token + +To verify and decode a JWT, use the following code: + +```java +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.SignatureException; + +public class JwtExample { + + private static final String SECRET_KEY = "your_secret_key"; + + public static Claims decodeToken(String token) { + try { + return Jwts.parser() + .setSigningKey(SECRET_KEY.getBytes()) + .parseClaimsJws(token) + .getBody(); + } catch (ExpiredJwtException e) { + System.out.println("Token has expired"); + } catch (SignatureException e) { + System.out.println("Invalid token"); + } + return null; + } + + public static void main(String[] args) { + String token = createToken("123", "example_user"); + System.out.println("Generated Token: " + token); + + Claims claims = decodeToken(token); + if (claims != null) { + System.out.println("Decoded Claims: " + claims); + } + } +} +``` + + + +### Installation + +First, add the `jwt` gem to your Gemfile: + +```ruby +gem 'jwt' +``` + +Then run: + +```bash +bundle install +``` + +Alternatively, you can install it directly using: + +```bash +gem install jwt +``` + +### Creating (Encoding) a Token + +To create a JWT, you need a payload (data) and a secret key. The payload can contain any data you need to include in the token, such as user information or claims. + +```ruby +require 'jwt' + +# Define the payload +payload = { + user_id: 123, + username: 'example_user', + exp: Time.now.to_i + 30 * 60 # Token expiration time (30 minutes from now) +} + +# Define the secret key +secret_key = 'your_secret_key' + +# Create the token +token = JWT.encode(payload, secret_key, 'HS256') + +puts "Generated Token: #{token}" +``` + +### Verifying (Decoding) a Token + +To verify a JWT, use the same secret key that was used to create the token. If the token is valid and has not expired, you can decode it to retrieve the payload. + +```ruby +require 'jwt' + +# Define the token you received +received_token = token + +# Define the secret key +secret_key = 'your_secret_key' + +# Decode the token +begin + decoded_payload = JWT.decode(received_token, secret_key, true, { algorithm: 'HS256' }) + puts "Decoded Payload: #{decoded_payload.first}" +rescue JWT::ExpiredSignature + puts "Token has expired" +rescue JWT::DecodeError + puts "Invalid token" +end +``` + + + + +### How to Created in the Token Backend Basic Example + + +
+

+

+ +
+
+ +
+
+ + + +#### Client-Side Implementation + +**Storing the Token Securely**: +- **localStorage**: + ```javascript + localStorage.setItem('token', token); + const token = localStorage.getItem('token'); + ``` + +- **sessionStorage**: + ```javascript + sessionStorage.setItem('token', token); + const token = sessionStorage.getItem('token'); + ``` + +- **Cookies** (Using `js-cookie` library): + 1. **Install the library**: + ```bash + npm install js-cookie + ``` + + 2. **Code to store and retrieve the token**: + ```javascript + const Cookies = require('js-cookie'); + + // Set a cookie + Cookies.set('token', token, { expires: 1 }); // 1 day expiration + + // Get a cookie + const token = Cookies.get('token'); + ``` + +**Sending the Token in Requests (Authorization Header)**: +1. **Using Fetch API**: + ```javascript + const token = localStorage.getItem('token'); + + fetch('https://your-api-endpoint.com', { + method: 'GET', + headers: { + 'Authorization': `Bearer ${token}` + } + }) + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error('Error:', error)); + ``` + +2. **Using Axios**: + 1. **Install Axios**: + ```bash + npm install axios + ``` + + 2. **Code to send a request with token**: + ```javascript + const axios = require('axios'); + + const token = localStorage.getItem('token'); + + axios.get('https://your-api-endpoint.com', { + headers: { + 'Authorization': `Bearer ${token}` + } + }) + .then(response => console.log(response.data)) + .catch(error => console.error('Error:', error)); + ``` + ### Example: + + + +
+
+

Backend

+
+

backend listen in 5000..

+
+
+
+

Frontend

+
+

Get to the data in backend use JWT

+

+ +

+        
+
+
+ \ No newline at end of file diff --git a/docs/JWT/security-Consideration.md b/docs/JWT/security-Consideration.md new file mode 100644 index 000000000..55017e170 --- /dev/null +++ b/docs/JWT/security-Consideration.md @@ -0,0 +1,109 @@ +--- +id: jwt-security +title: Security Considerations +sidebar_label: Security +sidebar_position: 5 +tags: [JWT, web development, Security] +description: Security Considerations in JWT. +--- + +#### Token Expiration and Revocation + +**Setting Expiration Times**: +- **Purpose**: Token expiration ensures that tokens are only valid for a specific period. This limits the time window in which a token can be used if compromised. +- **How to Set**: When creating a JWT, set the `exp` (expiration) claim to define when the token will expire. + +**Example (Node.js with `jsonwebtoken`)**: +```javascript +const token = jwt.sign(payload, secret, { expiresIn: '1h' }); // Token expires in 1 hour +``` + +- **Refresh Tokens**: Implement refresh tokens to allow users to obtain a new access token without re-authenticating. Refresh tokens usually have a longer expiration time than access tokens. + +**Token Revocation Strategies**: +- **Blacklisting**: Maintain a list of revoked tokens. This requires storing token identifiers (e.g., `jti`) and checking this list on every request. + + Example (Node.js): + ```javascript + const revokedTokens = new Set(); + + function isTokenRevoked(token) { + const decoded = jwt.decode(token); + return revokedTokens.has(decoded.jti); + } + + function revokeToken(token) { + const decoded = jwt.decode(token); + revokedTokens.add(decoded.jti); + } + ``` + +- **Short Expiry Times**: Use short-lived access tokens combined with longer-lived refresh tokens. This reduces the risk if a token is compromised. + +#### Securing the Token + +**Using HTTPS**: +- **Importance**: Always use HTTPS to encrypt the data transmitted between the client and server. This prevents token interception by attackers. +- **Implementation**: Ensure that your server is configured to support HTTPS and that clients access your API via `https://`. + +:::important +**Storing the Token Securely**: +- **LocalStorage**: Easy to use but vulnerable to XSS attacks. +- **SessionStorage**: Similar to `localStorage` but data is cleared when the page session ends. Still vulnerable to XSS. +- **Cookies**: Use cookies with the `HttpOnly` and `Secure` flags to mitigate XSS attacks and ensure the cookie is only sent over HTTPS. +::: + +**Example (Setting HttpOnly and Secure Flags in Express.js)**: +```javascript +app.use(cookieParser()); + +app.post('/login', (req, res) => { + const token = jwt.sign(payload, secret, { expiresIn: '1h' }); + res.cookie('token', token, { httpOnly: true, secure: true }); + res.send('Logged in'); +}); +``` +:::note +**Preventing Token Theft**: +- **Content Security Policy (CSP)**: Implement CSP to reduce the risk of XSS attacks. +- **Regular Audits**: Regularly review and update security practices and libraries. +- **Minimize Token Exposure**: Avoid exposing tokens in URLs, and always send them in headers. +::: + +#### Choosing the Right Algorithm + +**Symmetric (HMAC) vs. Asymmetric (RSA, ECDSA)**: +:::note +- **Symmetric (HMAC)**: + - **Algorithm**: Uses the same secret key for both signing and verification (e.g., HS256). + - **Benefits**: Faster and simpler since it requires only one key. + - **Use Cases**: Suitable for scenarios where you control both the issuing and verifying parties, such as in internal systems. + +- **Asymmetric (RSA, ECDSA)**: + - **Algorithm**: Uses a pair of keys: a private key for signing and a public key for verification (e.g., RS256, ES256). + - **Benefits**: More secure for scenarios where you need to share the verification key with multiple parties without exposing the signing key. + - **Use Cases**: Suitable for public APIs or scenarios where the verification and issuance of tokens are handled by different entities. +::: + + Example (HMAC with `jsonwebtoken`): + ```javascript + const token = jwt.sign(payload, 'your-256-bit-secret', { algorithm: 'HS256' }); + ``` + + Example (RSA with `jsonwebtoken`): + ```javascript + const fs = require('fs'); + const privateKey = fs.readFileSync('private.key'); + const publicKey = fs.readFileSync('public.key'); + + const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' }); + const decoded = jwt.verify(token, publicKey); + ``` + + +:::tip +1. **Set Token Expiration**: Define expiration times and use refresh tokens to manage sessions. +2. **Implement Revocation Strategies**: Use blacklisting or short-lived tokens to handle token revocation. +3. **Secure Token Storage**: Use HTTPS, store tokens securely, and prevent token theft. +4. **Choose the Right Algorithm**: Select between symmetric and asymmetric algorithms based on your security needs and architecture. +::: \ No newline at end of file