def test_decode_when_algorithm_not_available(self): token = jwt.encode(self.payload, PRIVATE_KEY, algorithm='RS256') pyjwt_without_rsa = PyJWS() pyjwt_without_rsa.unregister_algorithm('RS256') with patch.object(jwt, 'decode', new=pyjwt_without_rsa.decode): with self.assertRaisesRegex(TokenBackendError, 'Invalid algorithm specified'): self.rsa_token_backend.decode(token)
def test_decode_when_algorithm_not_available(): token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256') pyjwt_without_rsa = PyJWS() pyjwt_without_rsa.unregister_algorithm('RS256') with patch.object(jwt, 'decode', new=pyjwt_without_rsa.decode): with pytest.raises(TokenBackendError, match=r'Invalid algorithm specified'): rsa_token_backend.decode(token)
def test_decode_when_algorithm_not_available(self): token = jwt.encode(self.payload, PRIVATE_KEY, algorithm="RS256") if IS_OLD_JWT: token = token.decode("utf-8") pyjwt_without_rsa = PyJWS() pyjwt_without_rsa.unregister_algorithm("RS256") def _decode(jwt, key, algorithms, options, audience, issuer, leeway): return pyjwt_without_rsa.decode(jwt, key, algorithms, options) with patch.object(jwt, "decode", new=_decode): with self.assertRaisesRegex(TokenBackendError, "Invalid algorithm specified"): self.rsa_token_backend.decode(token)
def make_jws(_private_key, test_value: str): payload = json.dumps({'value': test_value}).encode('UTF-8') return PyJWS().encode( headers={'kid': TEST_KID}, payload=payload, key=_private_key, algorithm='RS256', )
def test_get_jwk(self, private_key): """Test that keys is fetched.""" jwks = make_jwks(private_key) jws = make_jws(private_key, 'TEST') responses.add( responses.GET, 'http://test.com', json=jwks, # noqa ) jwk = Jwks().get_jwk(jwt.get_unverified_header(jws)) assert PyJWS().decode( jws, jwk, options={'verify_signature': True}, )
class BigoneRestApi(object): """REST API""" jws = PyJWS() #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.apiKey = '' self.apiSecret = '' self.active = False self.reqid = 0 self.queue = Queue() self.pool = None self.sessionDict = {} # 会话对象字典 #---------------------------------------------------------------------- def init(self, apiKey, apiSecret): """初始化""" self.apiKey = str(apiKey) self.apiSecret = str(apiSecret) #---------------------------------------------------------------------- def start(self, n=10): """启动""" if self.active: return self.active = True self.pool = Pool(n) self.pool.map_async(self.run, range(n)) #---------------------------------------------------------------------- def close(self): """关闭""" self.active = False if self.pool: self.pool.close() self.pool.join() #---------------------------------------------------------------------- def addReq(self, method, path, callback, params=None, postdict=None): """添加请求""" self.reqid += 1 req = (method, path, callback, params, postdict, self.reqid) self.queue.put(req) return self.reqid #---------------------------------------------------------------------- def processReq(self, req, i): """处理请求""" method, path, callback, params, postdict, reqid = req url = REST_HOST + path header = {} header['Authorization'] = 'Bearer ' + self.generateSignature() try: # 使用长连接的session,比短连接的耗时缩短20% session = self.sessionDict[i] resp = session.request(method, url, headers=header, params=params, json=postdict) #resp = requests.request(method, url, headers=header, params=params, data=postdict) code = resp.status_code d = resp.json() if code == 200: callback(d, reqid) else: self.onError(code, str(d)) except Exception as e: self.onError(type(e), e.message) #---------------------------------------------------------------------- def run(self, i): """连续运行""" self.sessionDict[i] = requests.Session() while self.active: try: req = self.queue.get(timeout=1) self.processReq(req, i) except Empty: pass #---------------------------------------------------------------------- def generateSignature(self): """生成签名""" payload = '{"type":"OpenAPI","sub":"%s","nonce":%s}' %(self.apiKey, time()*1000000000) signature = self.jws.encode(payload, self.apiSecret) return signature #---------------------------------------------------------------------- def onError(self, code, error): """错误回调""" print('on error') print(code, error) #---------------------------------------------------------------------- def onData(self, data, reqid): """通用回调""" print('on data') print(data, reqid)
class ChainceRestApi(object): """""" jws = PyJWS() #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.jws.register_algorithm('Ed25519', EDAlgorithm()) self.apiKey = '' self.secretKey = '' self.active = False self.reqid = 0 self.queue = Queue() self.pool = None self.sessionDict = {} #---------------------------------------------------------------------- def init(self, apiKey, secretKey): """初始化""" self.apiKey = str(apiKey) self.secretKey = str(secretKey) #---------------------------------------------------------------------- def start(self, n=10): """启动""" if self.active: return self.active = True self.pool = Pool(n) self.pool.map_async(self.run, range(n)) #---------------------------------------------------------------------- def close(self): """关闭""" self.active = False if self.pool: self.pool.close() self.pool.join() #---------------------------------------------------------------------- def addReq(self, method, path, callback, params=None, postdict=None): """添加请求""" self.reqid += 1 req = (method, path, callback, params, postdict, self.reqid) self.queue.put(req) return self.reqid #---------------------------------------------------------------------- def processReq(self, req, i): """处理请求""" method, path, callback, params, postdict, reqid = req url = REST_HOST + path header = {'Authorization': 'Bearer %s' % self.generateSignature()} try: # 使用长连接的session,比短连接的耗时缩短20% resp = self.sessionDict[i].request(method, url, headers=header, params=params, json=postdict) code = resp.status_code d = resp.json() if code == 200: callback(d, req) else: self.onError(code, str(d)) except Exception as e: self.onError(type(e), e.message) #---------------------------------------------------------------------- def run(self, i): """连续运行""" s = requests.session() s.keep_alive = False self.sessionDict[i] = s while self.active: try: req = self.queue.get(timeout=1) self.processReq(req, i) except Empty: pass #---------------------------------------------------------------------- def generateSignature(self): """生成签名""" payload = '{"key": "%s", "iat": %s}' % (self.apiKey, int(time())) try: # py2 signature = self.jws.encode(payload, secretKey, algorithm='Ed25519') except TypeError: # py3 payload = bytes(payload, encoding="utf-8") bearer = self.jws.encode(payload, secretKey, algorithm='Ed25519') signature = str(bearer, encoding="utf-8") return signature #---------------------------------------------------------------------- def onError(self, code, error): """错误回调""" print('on error') print(code, error) #---------------------------------------------------------------------- def onData(self, data, req): """通用回调""" print('on %s' % req[1]) print(data, req[5])