The before code shows a simple request without authentication, which is insecure. The after code adds JWT token generation in Service A and token validation in Service B, ensuring only authorized requests succeed.
### Before: No service-to-service authentication
import requests
def call_service_b():
response = requests.get('http://service-b/api/data')
return response.json()
### After: Service-to-service authentication using JWT token
import requests
import jwt
import time
SECRET_KEY = 'shared-secret'
# Generate JWT token
def generate_token():
payload = {'iss': 'service-a', 'exp': int(time.time()) + 60}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
return token
# Call Service B with token
def call_service_b():
token = generate_token()
headers = {'Authorization': f'Bearer {token}'}
response = requests.get('http://service-b/api/data', headers=headers)
return response.json()
# Service B validates token
from flask import Flask, request, jsonify
import jwt
app = Flask(__name__)
@app.route('/api/data')
def data():
auth_header = request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return jsonify({'error': 'Unauthorized'}), 401
token = auth_header.split(' ')[1]
try:
jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'}), 401
return jsonify({'data': 'secure data'})