首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有PyJWT身份验证的酒瓶Restful

带有PyJWT身份验证的酒瓶Restful
EN

Stack Overflow用户
提问于 2019-09-26 01:17:15
回答 1查看 815关注 0票数 0

背景:

我正在尝试使用Flask和PyJWT构建一个快速的基于令牌的身份验证。这个想法是,我将有一个带有电子邮件和密码的表单,当用户单击submit时,它将生成一个令牌,并保存在客户端浏览器中,并在以后的任何请求中使用,直到令牌过期为止。

故障

在我的原型中,我能够使用JWT创建一个令牌,但我不知道如何将JWT传递到后续请求中。当我在Postman中这样做时,它可以工作,因为我可以在其中指定带有令牌的授权头。但是,当我通过UI登录并生成令牌时,我不知道如何将生成的令牌传递到后续请求(/protected)中,方法是使令牌保持在标头中直到过期。目前,当我从UI登录并转到/protected时,/protected头中缺少授权头。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2020-01-07 19:13:26

要持久化access_token,您必须在每次调用后端并检查令牌的真实性时,将其存储在客户端上并将其传递到标头。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58108324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档