背景:
我正在尝试使用Flask和PyJWT构建一个快速的基于令牌的身份验证。这个想法是,我将有一个带有电子邮件和密码的表单,当用户单击submit时,它将生成一个令牌,并保存在客户端浏览器中,并在以后的任何请求中使用,直到令牌过期为止。
故障
在我的原型中,我能够使用JWT创建一个令牌,但我不知道如何将JWT传递到后续请求中。当我在Postman中这样做时,它可以工作,因为我可以在其中指定带有令牌的授权头。但是,当我通过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发布于 2020-01-07 19:13:26
要持久化access_token,您必须在每次调用后端并检查令牌的真实性时,将其存储在客户端上并将其传递到标头。
https://stackoverflow.com/questions/58108324
复制相似问题