In a Flask API, returning a 401 Unauthorized status code is essential to indicate that a client request lacks valid authentication credentials. This status code informs the client that authentication is required to access the requested resource.
Implementing a 401 Unauthorized Response
To return a 401 status code in Flask, you can utilize the abort function from the flask module, which allows you to abort a request with a specific HTTP status code. Here's how you can implement it:
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
@app.route('/secure-endpoint')
def secure_endpoint():
auth = request.headers.get('Authorization')
if not auth or not validate_token(auth):
abort(401)
return jsonify({"message": "Welcome to the secure endpoint!"})
def validate_token(token):
# Implement your token validation logic here
return token == "Bearer ValidToken"
if __name__ == '__main__':
app.run()
In this example:
- The secure_endpoint function checks for the presence and validity of the Authorization header in the incoming request.
- If the header is missing or invalid, the abort(401) function is called, causing Flask to return a response with a 401 status code.
- The validate_token function contains the logic to verify the provided token.
Including the WWW-Authenticate Header
According to the HTTP specification, a 401 response should include a WWW-Authenticate header field, which defines the authentication method that should be used to access the requested resource. To include this header in your response, you can create a custom error handler for the 401 status code:
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
@app.errorhandler(401)
def unauthorized(error):
response = make_response(jsonify({'error': 'Unauthorized access'}), 401)
response.headers['WWW-Authenticate'] = 'Basic realm="Login required"'
return response
@app.route('/secure-endpoint')
def secure_endpoint():
auth = request.headers.get('Authorization')
if not auth or not validate_token(auth):
return unauthorized(None)
return jsonify({"message": "Welcome to the secure endpoint!"})
def validate_token(token):
# Implement your token validation logic here
return token == "Bearer ValidToken"
if __name__ == '__main__':
app.run()
In this modified example:
- An error handler for the 401 status code is registered using the @app.errorhandler(401) decorator.
- The unauthorized function creates a response with a 401 status code and includes the WWW-Authenticate header.
- The secure_endpoint function calls the unauthorized function when authentication fails.
Including the WWW-Authenticate header ensures that clients understand the authentication method required, which is particularly important for browsers and HTTP clients that automatically handle authentication challenges.