TL;DR
This guide shows you how to secure your REST API using access tokens. We’ll cover generating a token, sending it with requests, and verifying it on the server side.
1. Choose a Token Format (JWT)
JSON Web Tokens (JWTs) are a popular choice for access tokens. They’re self-contained and easy to work with. Other options exist but JWT is common.
2. Server-Side: Generating the Access Token
- Install a JWT library: For Python, you might use
PyJWT.pip install PyJWT - Create a secret key: This is crucial! Keep it safe and don’t hardcode it in your code. Use environment variables.
- Generate the token when a user logs in successfully: The token should contain information about the user (e.g., user ID) but *not* sensitive data like passwords.
import jwt import datetime secret_key = 'your-super-secret-key' payload = { 'user_id': 123, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour } token = jwt.encode(payload, secret_key, algorithm='HS256') print(token)
3. Client-Side: Sending the Access Token
After successful login, store the token (e.g., in local storage or a cookie). Include it in the Authorization header of every subsequent API request.
// Example using JavaScript's fetch API:
fetch('https://your-api.com/data', {
headers: {
'Authorization': 'Bearer ' + accessToken
}
})
.then(response => response.json())
.then(data => console.log(data));
Important: Use Bearer scheme for the token type.
4. Server-Side: Verifying the Access Token
- Extract the token from the header: Check for the
Authorizationheader. - Decode and verify the token: Use your JWT library to decode the token and check its signature against your secret key. Also, check if the token has expired.
import jwt secret_key = 'your-super-secret-key' token = request.headers.get('Authorization').split(' ')[1] # Assuming 'Bearer' format try: payload = jwt.decode(token, secret_key, algorithms=['HS256']) user_id = payload['user_id'] # Token is valid - proceed with the request except jwt.ExpiredSignatureError: # Token has expired - return an error except jwt.InvalidTokenError: # Invalid token - return an error - Handle invalid tokens: Return a
401 Unauthorizedstatus code if the token is missing, invalid, or expired.
5. Security Considerations
- HTTPS: Always use HTTPS to protect the token during transmission.
- Short Expiration Times: Keep tokens short-lived (e.g., 1 hour) and implement refresh tokens for longer sessions.
- Secret Key Management: Protect your secret key! Use environment variables, secure storage, or a dedicated secrets management service.
- Token Revocation: Implement a mechanism to revoke tokens if necessary (e.g., when a user logs out).

