背景:
我正在尝试使用 Flask-Restful 和 PyJWT 对基于令牌的快速身份验证进行原型设计。这个想法是我将有一个带有电子邮件和密码的表单,当用户单击提交时,它将生成一个令牌并将其保存在客户端浏览器中,并在任何后续请求中使用它,直到令牌过期。
麻烦
在我的原型中,我能够使用 JWT 创建一个令牌,但我不知道如何将 JWT 传递给后续请求。当我在 Postman 中执行此操作时,它可以工作,因为我可以在其中指定带有令牌的 Authorization 标头。但是当我通过 UI 登录并生成令牌时,我不知道如何通过使令牌在标头中持续存在直到它过期来将生成的令牌传递到后续请求(/protected)中。目前,当我从 UI 登录并转到 /protected 时,/protected 标头中缺少授权标头。
代码
class LoginAPI(Resource):
# added as /login
def get(self):
"""
renders a simple HTML with email and password in a form.
"""
headers = {'Content-Type': 'text/html'}
return make_response(render_template('login.html'), 200, headers)
def post(self):
email = request.form.get('email')
password = request.form.get('password')
# assuming the validation has passed.
payload = {
'user_id': query_user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
}
token = jwt\
.encode(payload, current_app.config['JWT_SECRET'], current_app.config['JWT_ALGORITHM'])\
.decode('utf-8')
# Is below the right way to set the token into header to be used in subsequent request?
# request.headers.authorization = token
# when {'authorization': token} below as a header, the header only shows up for /login not for any subsequent request.
return make_response({'result': 'success', 'token': token}, 200, {'authorization': token} )
class ProtectedAPI(Resource):
@check_auth
def get(self):
return jsonify({'result': 'success', 'message': 'this is a protected view.'})
# decorator to check auth and give access to /protected
def check_auth(f):
@wraps(f)
def authentication(*args, **kws):
# always get a None here.
jwt_token = request.headers.get('authorization', None)
payload = jwt.decode(jwt_token, 'secret_key', algorithms='HS512'])
# other validation below skipped.
return f(*args, **kws)
return authentication