# jwt

***

**1. JWT Verification with Express.js**

```javascript
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

app.post('/authenticate', (req, res) => {
  const token = jwt.sign({ id: 'admin' }, 'mySecretKey');
  res.json({ token });
});

app.get('/protected', (req, res) => {
  const token = req.headers['authorization'];
  jwt.verify(token, 'mySecretKey', (err, decoded) => {
    if (err) {
      res.status(401).send('Unauthorized');
    } else {
      res.send(`Welcome back, ${decoded.id}!`);
    }
  });
});

app.listen(3000);
```

**2. JWT Issuance and Validation in Node.js**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id', role: 'admin' };
const token = jwt.sign(payload, secret);

const decoded = jwt.verify(token, secret);
console.log(decoded); // { id: 'user_id', role: 'admin' }
```

**3. JWT Authentication in a REST API**

```javascript
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const secretKey = 'mySecretKey';

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  // Authenticate the user (e.g., check credentials against a database)
  const token = jwt.sign({ username }, secretKey);
  res.json({ token });
});

app.get('/protected', (req, res) => {
  const token = req.headers['authorization'];
  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      res.status(401).send('Unauthorized');
    } else {
      res.send(`Welcome back, ${decoded.username}!`);
    }
  });
});

app.listen(3000);
```

**4. JWT for Role-Based Authorization**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id', role: 'admin' };
const token = jwt.sign(payload, secret);

// In a protected route:
const decoded = jwt.verify(token, secret);
if (decoded.role !== 'admin') {
  // Unauthorized
}
```

**5. JWT for Single Sign-On (SSO)**

```javascript
const jwt = require('jsonwebtoken');
const secretKey = 'mySecretKey';

// On the server side:
const payload = { id: 'user_id' };
const token = jwt.sign(payload, secretKey);

// On the client side:
window.localStorage.setItem('token', token);

// On every request to a protected route:
const token = window.localStorage.getItem('token');
const requestHeaders = {
  ...headers,
  Authorization: `Bearer ${token}`,
};
```

**6. JWT with HMAC Algorithm**

```javascript
const jwt = require('jsonwebtoken');
const secret = Buffer.from('mySecretKey');

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { algorithm: 'HS256' });
```

**7. JWT with RSA Algorithm**

```javascript
const jwt = require('jsonwebtoken');
const fs = require('fs');

const privateKey = fs.readFileSync('private.key');
const publicKey = fs.readFileSync('public.key');

const payload = { id: 'user_id' };
const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' });
```

**8. JWT with Expiry Time**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
```

**9. JWT with Not Before Time**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { notBefore: '10m' });
```

**10. JWT with Audience**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { audience: 'myAudience' });
```

**11. JWT with Issuer**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { issuer: 'myIssuer' });
```

**12. JWT with Subject**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { subject: 'mySubject' });
```

**13. JWT with JWT ID**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { jti: 'myJWTID' });
```

**14. JWT with Headers**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { header: { alg: 'HS256', typ: 'JWT' } });
```

**15. JWT with Claims**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id', customClaim: 'myCustomClaim' };
const token = jwt.sign(payload, secret);
```

**16. JWT with Custom Options**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { noTimestamp: true, expiresIn: 0 });
```

**17. JWT with Multiple Signatures**

```javascript
const jwt = require('jsonwebtoken');
const secretKey1 = 'mySecretKey1';
const secretKey2 = 'mySecretKey2';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secretKey1, { algorithm: 'HS256' });
const token2 = jwt.sign(payload, secretKey2, { algorithm: 'HS256' });
```

**18. JWT with Refresh Tokens**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id', refresh: true };
const token = jwt.sign(payload, secret);
```

**19. JWT with Token Expiration**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { expiresIn: 300 });
```

**20. JWT with Token Revocation**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';
const revokedTokens = [];

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret);
revokedTokens.push(token);
```

**21. JWT with Token Blacklist**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';
const blacklist = [];

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret);
blacklist.push(token);
```

**22. JWT with Token Introspection**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret);

jwt.verify(token, secret, (err, decoded) => {
  if (!err) {
    // Token is valid and has not expired
  } else {
    // Token is invalid or expired
  }
});
```

**23. JWT with Token Whitelist**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';
const whitelist = [];

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret);
whitelist.push(token);
```

**24. JWT with Token Renewal**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';

const payload = { id: 'user_id' };
const token = jwt.sign(payload, secret, { expiresIn: 300 });

setTimeout(() => {
  // Renew the token
  const newToken = jwt.sign(payload, secret, { expiresIn: 300 });
}, 250);
```

**25. JWT with Token Rotation**

```javascript
const jwt = require('jsonwebtoken');
const secret = 'mySecret';
const privateKey = fs.readFileSync('private.key');
const publicKey = fs.readFileSync('public.key');

// Rotate the secret key periodically
setInterval(() => {
  const newSecret = generateNewSecretKey();
  // Sign the tokens with the new secret key
  const newTokens = jwt.signAll(payloads, newSecret, { algorithm: 'HS256' });
}, 3600);
```
