The before code shows each microservice checking the token, causing duplication. The after code moves authentication to the gateway, which checks the token once before forwarding requests. Microservices trust the gateway and do not perform authentication themselves.
### Before: Authentication inside each microservice (naive)
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/data')
def data():
token = request.headers.get('Authorization')
if not token or token != 'valid-token':
return jsonify({'error': 'Unauthorized'}), 401
return jsonify({'data': 'secret data'})
### After: Authentication at API Gateway (centralized)
# Gateway code
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.before_request
def authenticate():
token = request.headers.get('Authorization')
if not token or token != 'valid-token':
return jsonify({'error': 'Unauthorized'}), 401
@app.route('/proxy/<path:path>')
def proxy(path):
# Forward request to microservice without auth check
# (simplified example)
return jsonify({'data': 'secret data from microservice'})
# Microservice code (no auth needed)
from flask import Flask, jsonify
microservice = Flask(__name__)
@microservice.route('/data')
def data():
return jsonify({'data': 'secret data'})