简体   繁体   中英

Should server-side methods throw exceptions if access is forbidden?

I have an (jQuery) AJAX call in my Javascript that calls a Python method serverside that verifies if a person has credentials, then the Python sends back the information required.

If either the person is not logged in or does not have credentials, it throws an error and I catch the error with the error block in my jQuery AJAX function, telling the user that an error happened.

My problem is that I'm not able to display what kind of error, just that an error occurred and a 500 code was returned by the server. Should I have the method complete successfully even when the user does not have credentials, instead returning a message that says 'forbidden' or 'not logged in' instead of the data required?

Basically my question is, should I force the method to throw an exception when a user does not have authorization to access some information?

Yes, you should throw an exception. You should not return a successful response on a server error as consumer of the service might not be aware you are actually storing specific information whether or not it was an error, and if so, of what type.

Furthermore, you could modify the response message to sent back HTTP 403 , which actually conveys an authorization failure.

A 401 error is used for authentication, and 403 is for authorization. The flasky way to do this is with custom error handlers:

from flask import Flask, abort, Response, jsonify
app = Flask(__name__)


@app.errorhandler(403)
def not_authorized(e):
    response = jsonify({'code': 403,'message': 'Not damn authorized'})
    response.status_code = 403
    return response


@app.errorhandler(401)
def not_authenticated(e):
    response = jsonify({'code': 401,'message': 'Not damn authenticated'})
    response.status_code = 401
    return response

@app.route("/unauthorized")
def unauthorized():
    abort(403)


@app.route("/unauthenticated")
def unauthenticated():
    abort(401)


@app.route("/")
def index():
    return jsonify({"message":"hello world!"})

#Another way to do it perhaps, without using global error handler functions. 
@app.route("/test/<var>")
def test(var):
    if var == 1:
        response = jsonify({'code': 403,'message': 'Not damn authorized'})
        response.status_code = 403
        return response
    else:
        response = jsonify({'code': 403,'message': 'Some other message'})
        response.status_code = 403
        return response


if __name__ == "__main__":
    app.run(port=8080, debug=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM