-
Notifications
You must be signed in to change notification settings - Fork 74
Description
Security Enhancements
Use Strong Signing Algorithms: Use HS256 or RS256 for JWT tokens.
Set Expiry Time (exp): Avoid long-lived tokens. Use short expiration with refresh tokens.
Use Refresh Tokens: Keep access tokens short-lived and refresh them securely.
Include Audience (aud) and Issuer (iss): Helps verify who the token is for and who issued it.
Rotate Secrets: Regularly rotate signing keys or secrets.
Use HTTPS: Always transmit tokens over secure HTTPS to prevent sniffing.
Limit Scope: Use scopes or claims to restrict access to necessary resources only.
Store Securely: Don’t store tokens in localStorage (XSS risk); prefer HTTP-only cookies.
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, create_refresh_token
If access token expires
@app.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
identity = get_jwt_identity()
return jsonify(access_token=create_access_token(identity=identity)), 200
async function fetchWithAuth() {
try {
const res = await fetch('/api/data', {
headers: { Authorization: Bearer ${accessToken}
}
});
if (res.status === 401) {
// Token expired, try refresh
const refreshRes = await fetch('/refresh', { method: 'POST' });
const { access_token } = await refreshRes.json();
accessToken = access_token;
return fetchWithAuth(); // retry with new token
}
return await res.json();
} catch (err) {
console.error('Fetch failed:', err);
}
}