I'm currently developing a JavaScript client-side app to interact with a Flask RESTful API. I've implemented some methods that require user authentication, but for some reason, even after logging into the server, I receive a 401 error (Unauthorized) when trying to call these methods.
Below are snippets of the code related to the login process on the Flask server:
Authentication method where user credentials are verified:
@auth.verify_password
def verify_password(email, password):
user = User.query.filter_by(email=email).first()
if not user:
return False
g.user = user
return flask_bcrypt.check_password_hash(user.password, password)
Authentication View for handling POST requests:
class SessionView(restful.Resource):
def post(self):
form = SessionCreateForm()
if not form.validate_on_submit():
return form.errors, 422
user = User.query.filter_by(email=form.email.data).first()
if user and flask_bcrypt.check_password_hash(user.password, form.password.data):
return UserSerializer(user).data, 201
return '', 401
Snippet of the JS client-side login function using an AJAX POST request:
function logar() {
// Function implementation...
}
Further down in the code, there's another method 'PurchaseView' which requires authentication to execute:
class PurchaseView(restful.Resource):
@auth.login_required
def post(self):
// Code implementation...
The issue arises when trying to execute the 'PurchaseView' method via an AJAX call:
$.ajax({
// AJAX call configuration...
})
.success(function(result) {
// Success callback function...
})
.error(function(result) {
alert("Error");
});
List of defined resources within the Flask API:
api.add_resource(UserView, '/api/v1/users')
// Remaining resources listed here...
Curl command snippet along with HTTP response header that leads to a 401 Unauthorized status:
curl 'http://localhost:5000/api/v1/purchase' -H 'Origin: http://localhost:8000'
// Additional curl command details provided in the original text...
HTTP/1.0 401 UNAUTHORIZED
Content-Type: text/html; charset=utf-8
// Other headers included in the HTTP response...