我正在使用烧瓶 restful 构建烧瓶应用程序。使用 flask_jwt_extended 模块生成访问令牌。我能够生成 access_token ,refresh_token,但是在访问 API 时会引发以下错误,我在请求标头中传递了 access_token。
127.0.0.1 - - [23/Apr/2020 13:44:35] "POST /api/protected HTTP/1.1" 405 -
[2020-04-23 13:44:44,742] ERROR in app: Exception on /api/protected [GET]
Traceback (most recent call last):
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask_restful/__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask_restful/__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 107, in wrapper
verify_jwt_in_request()
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 32, in verify_jwt_in_request
jwt_data, jwt_header = _decode_jwt_from_request(request_type='access')
File "/home/hasher/test_jwt/env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 314, in _decode_jwt_from_request
raise NoAuthorizationError(errors[0])
flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header
127.0.0.1 - - [23/Apr/2020 13:44:44] "GET /api/protected HTTP/1.1" 50
- 下面是应用代码。
from flask import Flask, jsonify, request
from flask_restful import Api
from flask_restful import Resource
from flask_jwt_extended import (
JWTManager,
jwt_required,
create_access_token,
jwt_refresh_token_required,
create_refresh_token,
get_jwt_identity,
)
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "super-secret" # Change this!
jwt = JWTManager(app)
api = Api(app)
class Login(Resource):
def post(self):
import pdb
pdb.set_trace()
username = request.json.get("username", "test")
password = request.json.get("password", "test")
ret = {
"access_token": create_access_token(identity=username),
"refresh_token": create_refresh_token(identity=username),
}
return ret
class Refresh(Resource):
@jwt_refresh_token_required
def post(self):
current_user = get_jwt_identity()
ret = {"access_token": create_access_token(identity=current_user)}
return ret
class Protected(Resource):
@jwt_required
def get(self):
username = get_jwt_identity()
return dict(logged_in_as=username)
api.add_resource(Login, "/api/login")
api.add_resource(Refresh, "/api/refresh")
api.add_resource(Protected, "/api/protected")
if __name__ == "__main__":
app.run()