authlib / example-oauth2-server

Example for OAuth 2 Server for Authlib.
https://authlib.org/
684 stars 285 forks source link

How do you customize error messages #97

Closed mingganglee closed 1 year ago

mingganglee commented 1 year ago

{"error": "invalid_token", "error_description": "The access token provided is expired, revoked, malformed, or invalid for other reasons."}

mingganglee commented 1 year ago

customize error messages

@bp.after_request
def after_handler(response):
    match response.status_code:
        case 200:
            # retunr 200 status_code
            return response
        case 500:
            # return 500 status_code
            return response
        case _:
            # handling other status_code
            data = loads(response.data)

            # check data key
            if "error" in data:

                # change status_code to 200
                response.status_code = 200

                # handling custom message
                match data["error"]:
                    case "invalid_token":
                        response.data = dumps({"code": 401, "msg": "invalid_token"})
                    case "invalid_request":
                        response.data = dumps({"code": 401, "msg": "invalid_request"})
                    case "invalid_client":
                        response.data = dumps({"code": 401, "msg": "invalid_client"})
                    case "missing_authorization":
                        response.data = dumps({"code": 401, "msg": "missing_authorization"})
                    case _:
                        response.data = dumps({"code": 500, "msg": "system error"})

            return response