JSON Web Tokens (JWT) require a secret key for signing and verification when using symmetric algorithms like HS256. The strength of your JWT security directly depends on the secrecy and randomness of this key.
What is JWT JWT_SECRET?
A JWT secret key is used to create and verify the signature portion of JSON Web Tokens. For symmetric algorithms (HS256, HS384, HS512), the same key is used for both signing and verification. The key must remain secret to prevent token forgery.
Key Requirements
- At least 256 bits (32 bytes) for HS256
- At least 384 bits (48 bytes) for HS384
- At least 512 bits (64 bytes) for HS512
- Must be cryptographically random
- Should be URL-safe for ease of use
How to Use
Use the generated key with your JWT library:
```javascript
// Node.js with jsonwebtoken
const jwt = require('jsonwebtoken');
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: '1h',
algorithm: 'HS256'
});
```
```python
# Python with PyJWT
import jwt
token = jwt.encode(payload, os.environ['JWT_SECRET'], algorithm='HS256')
```Best Practices
- Use a key length appropriate for your algorithm
- Implement token expiration (exp claim)
- Consider using asymmetric keys (RS256) for microservices
- Include issuer (iss) and audience (aud) claims
- Implement token refresh for long-lived sessions
Common Mistakes to Avoid
- โUsing keys shorter than the algorithm requires
- โNot setting token expiration times
- โStoring sensitive data in the JWT payload
- โNot validating all claims on verification
- โUsing JWT for session management without proper invalidation