def wrapper(*args, **kwargs): # 补全代码 print(request.method) if self.admin: if request.method == 'POST': data = request.form else: data = request.args token = request.headers.get('Authorization', '')[4:] or data.get('token', '') User.verify_token(token=token, verify_exp=self.verify_exp) return func(*args, **kwargs)
def test_verify_token(self, user): """测试 User.verify_token 类方法 """ # 成功验证 token token = user.generate_token() # 验证 token 成功后会返回 User 对象 u = User.verify_token(token) assert user == u
def wrapper(*args, **kwargs): # 补全代码 jwt_token = request.headers.get('Authorization') if jwt_token is not None: jwt_token = jwt_token.split(" ")[-1] else: jwt_token = request.form.get('token') if jwt_token is None: jwt_token = request.args.get('token') if jwt_token is None: raise RestError(403, 'token not exist') g.instance = User.verify_token(jwt_token) return func(*args, **kwargs)
def test_login_success(self, client, admin): """登录成功 """ data = {'name': admin.name, 'password': PASSWORD} resp = client.post(url_for(self.endpoint), data=json.dumps(data), headers={'Content-Type': 'application/json; utf-8'}) assert resp.status_code == 200 assert resp.json['ok'] == True # 获取到的 token 成功验证 u = User.verify_token(resp.json['token']) assert u == admin
def test_generate_token(self, user, app): """测试 User.generate_token 方法 """ now = timegm(datetime.utcnow().utctimetuple()) token = user.generate_token() payload = jwt.decode(token, verify=False) assert payload['uid'] == user.id assert payload['is_admin'] == user.is_admin assert 'refresh_exp' in payload assert 'exp' in payload # 生成的 token 有效期为一天 assert payload['exp'] - now == 24 * 3600 # token 过期后十分钟内,还可以使用老 token 进行刷新 token assert payload['refresh_exp'] - now == 24 * 3600 + 10 * 60 u = User.verify_token(token) assert u == user
def test_verify_token_failed(self, user, app): """测试 User.verify_token 验证 token 时失败 """ algorithm = 'HS512' # token 验证失败 invalid_token = user.generate_token() + '0' try: User.verify_token(invalid_token) except InvalidTokenError as e: assert e.code == 403 assert 'Signature' in e.message # token 指定的用户不存在 exp = datetime.utcnow() + timedelta(days=1) # token 过期后十分钟内,还可以使用老 token 进行刷新 token refresh_exp = timegm((exp + timedelta(seconds=60 * 10)).utctimetuple()) # 用户步存在 user_not_exist = 100 payload = { 'uid': user_not_exist, 'is_admin': False, 'exp': exp, 'refresh_exp': refresh_exp } # 用户不存在 try: User.verify_token( jwt.encode(payload, app.secret_key, algorithm=algorithm)) except InvalidTokenError as e: assert e.code == 403 assert e.message == 'user not exist' payload = {'exp': exp} try: User.verify_token( jwt.encode(payload, app.secret_key, algorithm=algorithm)) except InvalidTokenError as e: assert e.code == 403 assert e.message == 'invalid token' # token 刷新时间无效 refresh_exp = datetime.utcnow() - timedelta(days=1)
def wrapper(*args, **kwargs): pack = request.headers.get('Authorization', None) if pack is None: raise AuthenticationError(401, 'token not found') parts = pack.split() # Authorization 头部值必须为 'jwt <token_value>' 这种形式 if parts[0].lower() != 'jwt': raise AuthenticationError(401, 'invalid token header') elif len(parts) == 1: raise AuthenticationError(401, 'token missing') elif len(parts) > 2: raise AuthenticationError(401, 'invalid token') token = parts[1] user = User.verify_token(token, verify_exp=self.verify_exp) # 如果需要验证是否是管理员 if self.admin and not user.is_admin: raise AuthenticationError(403, 'no permission') # 将当前用户存入到 g 对象中 g.user = user return func(*args, **kwargs)