-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Authentication - where, what, how? #1
Comments
For GET/POST requests from indicia (or other service) to the API see this from chatgpt: You can use a Python decorator to handle authentication for your Flask routes in a clean and reusable way. A decorator allows you to apply the same authentication logic across multiple routes without repeating code. 1. Create the Authentication Decorator
2. Apply the Decorator to Your Routes
Example Implementationfrom functools import wraps
from flask import Flask, request, jsonify
app = Flask(__name__)
# A dictionary to store tokens for simplicity. In a production environment, store these in a database.
VALID_TOKENS = {
"service1": "your_token_for_service1",
"service2": "your_token_for_service2",
# Add more tokens for other services
}
def check_auth(token):
"""Check if the token is valid."""
return token in VALID_TOKENS.values()
def auth_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
auth_header = request.headers.get('Authorization')
if not auth_header:
return jsonify({"message": "Missing token"}), 401
# The token is usually sent as "Bearer <token>"
try:
token = auth_header.split(" ")[1]
except IndexError:
return jsonify({"message": "Invalid token format"}), 401
# Validate the token
if not check_auth(token):
return jsonify({"message": "Unauthorized"}), 401
# If the token is valid, proceed with the original function
return f(*args, **kwargs)
return decorated_function
@app.route('/your_api_endpoint', methods=['POST'])
@auth_required
def your_api_function():
# Your API logic here
data = request.json
return jsonify({"message": "Data received", "data": data}), 200
@app.route('/another_endpoint', methods=['POST'])
@auth_required
def another_api_function():
# Logic for another endpoint
data = request.json
return jsonify({"message": "Another endpoint hit", "data": data}), 200
if __name__ == '__main__':
app.run(debug=True) Explanation:
Usage:
This approach keeps your authentication logic centralized and reusable, making your codebase cleaner and easier to maintain. |
No description provided.
The text was updated successfully, but these errors were encountered: