Security essentials for Flask APIs — CORS, Talisman security headers, rate
99
94%
Does it follow best practices?
Impact
100%
1.17xAverage score across 10 eval scenarios
Passed
No known issues
A company's internal HR portal uses a Flask API to serve employee data. The team needs to add session-based authentication: after a successful login, the server should remember who the user is across requests.
The developer tasked with this has a rough skeleton in place but hasn't finished the implementation. The portal will be deployed to production behind HTTPS.
Your job is to complete the session management implementation in portal.py. The login route already validates credentials against a hard-coded dict (acceptable for this prototype). You need to finish configuring the session layer and implement the login handler so the /me endpoint works correctly.
Produce a single updated file:
portal.py — the completed Flask application with session managementThe following file is provided as input. Extract it before beginning.
=============== FILE: portal.py =============== import os from flask import Flask, jsonify, request, session
USERS = { 'alice': { 'password': 'hunter2', 'role': 'admin', 'salary_band': 'L5', 'hr_api_token': 'tok_alice_abc123', }, 'bob': { 'password': 'correct-horse', 'role': 'viewer', 'salary_band': 'L3', 'hr_api_token': 'tok_bob_xyz789', }, }
def create_app(): app = Flask(name) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') if not app.config['SECRET_KEY'] and not app.config.get('TESTING'): raise RuntimeError('SECRET_KEY environment variable is required')
# TODO: configure session settings for production
@app.route('/login', methods=['POST'])
def login():
data = request.get_json(silent=True)
if data is None:
return jsonify({'error': 'Request body must be JSON'}), 400
username = data.get('username', '')
password = data.get('password', '')
user = USERS.get(username)
if not user or user['password'] != password:
return jsonify({'error': 'Invalid credentials'}), 401
# TODO: store user data in the session so /me works
return jsonify({'message': 'Logged in'}), 200
@app.route('/me', methods=['GET'])
def me():
user_id = session.get('user_id')
if not user_id:
return jsonify({'error': 'Not authenticated'}), 401
return jsonify({'user_id': user_id}), 200
@app.route('/logout', methods=['POST'])
def logout():
session.clear()
return jsonify({'message': 'Logged out'}), 200
return appif name == 'main': app = create_app() app.run()
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
skills
flask-security-basics
verifiers