如何在Google App Engine(Python)上使用JWT对用户名进行标记?

时间:2015-01-25 20:00:38

标签: python google-app-engine webapp2 jwt

我正在尝试让我的后端服务器签名,并在OAuth请求结束时发送用户名。我尝试关注的示例使用此程序包(https://www.npmjs.com/package/express-jwt),但我的后端位于Google App Engine中。所以,我想知道如何在App Engine / webapp2框架内实现相同的功能(用一些秘密签名用户名)?

1 个答案:

答案 0 :(得分:1)

首先将python jwt下载到项目的文件夹lib

代码:

import cgi
import datetime
import webapp2
from base_handler import BaseRequestHandler, login_required
from webapp2 import Route
from models import Customer
from lib import jwt
import logging

def login_required(fn):
    def check(self, *args, **kargs):
        auth = self.request.headers.get('Authorization')
        login_info = jwt.decode(auth, 'secret', algorithms=['HS256'])
        # your verify login token here
        logging.error(login_info)
        # verify success
        fn(self, *args, **kargs)
    return check


class LoginHandler(BaseRequestHandler):
    def login(self):
        username = self.request.get('username')
        password = self.request.get('password')
        if Customer.login(username, password) is True:
            encoded = jwt.encode({'username': username}, 'secret', algorithm='HS256')
            self.response.write({'token': encoded})
            return

        self.response.write('login unsuccess', status=404)


class APIHandler(BaseRequestHandler):
    @login_required
    def get(self):
        self.response.write('product found')


app = webapp2.WSGIApplication([
    Route('/login', handler=LoginHandler, handler_method='login', name='login', methods=['POST']),
      ('/', APIHandler)
], debug=True)

注意:对于测试客户端,您可以使用postman并添加标头(令牌来自登录请求)