Configuration – JWT Settings
An essential aspect of securing our RESTful API is configuring JSON Web Token (JWT) authentication. This section dives deep into how JWT is set up in magarrent/REST-API-PYTHON-demo, covering:
- Index
- Secret Key
- JWT Initialization
- Authentication Endpoint
- Security Functions
- Authentication Workflow (Diagram)
- Customization & Advanced Settings
Index
- Secret Key
- JWT Initialization
- Authentication Endpoint
- Security Functions
- Authentication Workflow
- Customization & Advanced Settings
1. Secret Key
app.secret_key defines the secret used to sign all JWT tokens (and Flask sessions). Keeping this value confidential is critical—exposure compromises the integrity of issued tokens.
# PYTHON/app.py
app = Flask(__name__)
# … other config …
app.secret_key = 'SapanCrackle'
- Location:
PYTHON/app.py - Purpose:
- Cryptographically sign JWTs (HMAC-SHA256 by default).
- Secure Flask session cookies if used.
2. JWT Initialization
The flask_jwt extension wires up authentication via a single line:
# Mounts /auth endpoint using the 'authenticate' and 'identity' handlers
jwt = JWT(app, authenticate, identity) # /auth
- Location:
PYTHON/app.py - What It Does:
- Registers a POST
/authroute. - Expects JSON
{ "username": ..., "password": ... }. - Calls
authenticate(username, password)to verify credentials. - Issues a signed JWT in response (
access_token). - Hooks
identity(payload)to protect subsequent requests.
- Registers a POST
3. Authentication Endpoint
All JWT-related requests occur against the automatically mounted /auth endpoint.
{
"title": "Obtain JWT Access Token",
"description": "Exchange valid credentials for a signed JWT.",
"method": "POST",
"baseUrl": "http://localhost:5000",
"endpoint": "/auth",
"headers": [
{ "key": "Content-Type", "value": "application/json", "required": true }
],
"pathParams": [],
"queryParams": [],
"bodyType": "json",
"requestBody": "{\n \"username\": \"sapan\",\n \"password\": \"sapan1234\"\n}",
"responses": {
"200": {
"description": "Token issued successfully",
"body": "{\n \"access_token\": \"<jwt_token>\"\n}"
},
"401": {
"description": "Invalid credentials",
"body": "{\n \"message\": \"Invalid credentials\"\n}"
}
}
}
4. Security Functions
Two application-specific handlers drive JWT operations:
| Function | Location | Responsibility |
|---|---|---|
authenticate |
PYTHON/security.py |
Verify username/password; return UserModel on success. |
identity |
PYTHON/security.py |
Extract user identity from JWT payload; return UserModel. |
# PYTHON/security.py
from werkzeug.security import safe_str_cmp
from models.user import UserModel
def authenticate(username, password):
user = UserModel.find_by_username(username)
if user and safe_str_cmp(user.password, password):
return user
def identity(payload):
user_id = payload['identity']
return UserModel.find_by_id(user_id)
- Credential Check: uses
safe_str_cmpfor timing-attack-resistant password comparison. - Identity Lookup: reads the
identityclaim from token payload.
5. Authentication Workflow
Below is a high-level sequence diagram illustrating the JWT flow from login to resource access.
sequenceDiagram
participant Client
participant API
participant Security
Client->>API: POST /auth { username, password }
API->>Security: authenticate(username, password)
Security-->>API: returns UserModel
API-->>Client: { access_token: "<JWT>" }
Client->>API: GET /book/{title}\nAuthorization: JWT <JWT>
API->>Security: identity(decoded_payload)
Security-->>API: returns UserModel
API-->>Client: 200 OK + resource
6. Customization & Advanced Settings
While this demo uses default JWT behavior, flask_jwt allows fine-tuning via Flask configuration keys:
| Config Key | Default | Description |
|---|---|---|
JWT_AUTH_URL_RULE |
'/auth' |
URL rule for auth endpoint |
JWT_AUTH_USERNAME_KEY |
'username' |
JSON key for username in auth request |
JWT_AUTH_PASSWORD_KEY |
'password' |
JSON key for password in auth request |
JWT_AUTH_HEADER_PREFIX |
'JWT' |
Prefix for Authorization header |
JWT_EXPIRATION_DELTA |
300 seconds | Token lifetime |
JWT_HEADER_NAME |
'Authorization' |
Header name to read token from |
To override, simply set in your Flask app before (JWT(...)):
app.config['JWT_AUTH_URL_RULE'] = '/login'
app.config['JWT_EXPIRATION_DELTA'] = timedelta(hours=1)
app.config['JWT_AUTH_HEADER_PREFIX'] = 'Bearer'
Summary:
app.secret_key: anchors JWT signingJWT(app, authenticate, identity): auto-mounts/authauthenticate/identity: secure credential and payload handling.- Optional configs exist for customizing URL rules, expiration, and header formats.