def validate(self, jwt, iss, aud): parts = jwt.split('.') if len(parts) != 3: raise BadSignature('Invalid JWT. Only JWS supported.') header = json.loads(base64_urldecode(parts[0])) payload = json.loads(base64_urldecode(parts[1])) # FIXME: Microsoft returns {tenantid} in issuer, we must replace _iss = iss if '{tenantid}' in _iss: if 'tid' in payload: _iss = _iss.replace('{tenantid}', payload['tid']) else: raise JwtValidatorException( "Tenant {tenantid} specified in issuer, but no tid in payload" ) if _iss != payload['iss']: raise JwtValidatorException("Invalid issuer %s, expected %s" % (payload['iss'], _iss)) if payload["aud"]: if (isinstance(payload["aud"], str) and payload["aud"] != aud) or aud not in payload['aud']: raise JwtValidatorException( "Invalid audience %s, expected %s" % (payload['aud'], aud)) jws = JWS(alg=header['alg']) # Raises exception when signature is invalid try: jws.verify_compact(jwt, self.jwks) except Exception as e: print "Exception validating signature" raise JwtValidatorException(e) print "Successfully validated signature."
def test_a_1_3b(): _jwt = ("eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJl" "eHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0c" "nVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") keys = [SYMKey(key=jwkest.intarr2bin(HMAC_KEY))] _jws2 = JWS() _jws2.verify_compact(_jwt, keys)
def test_issued_software_statement_contains_kid(self): federation = Federation(self.signing_key) jws = federation.create_software_statement({}) _jws = JWS() _jws.verify_compact(jws, keys=[self.signing_key]) assert _jws.jwt.headers["kid"] == self.signing_key.kid
def test_a_1_3b(): _jwt = ("eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJl" "eHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0c" "nVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") keys = [SYMKey(key=jwkest.intarr2bin(HMAC_KEY))] _jws2 = JWS() _jws2.verify_compact(_jwt, keys)
def validate(self, jwt, iss, aud): parts = jwt.split('.') if len(parts) != 3: raise BadSignature('Invalid JWT. Only JWS supported.') header = json.loads(base64_urldecode(parts[0])) payload = json.loads(base64_urldecode(parts[1])) if iss != payload['iss']: raise JwtValidatorException("Invalid issuer %s, expected %s" % (payload['iss'], iss)) if payload["aud"]: if (isinstance(payload["aud"], str) and payload["aud"] != aud) or aud not in payload['aud']: raise JwtValidatorException( "Invalid audience %s, expected %s" % (payload['aud'], aud)) jws = JWS(alg=header['alg']) # Raises exception when signature is invalid try: jws.verify_compact(jwt, self.jwks) except Exception as e: print "Exception validating signature" raise JwtValidatorException(e) print "Successfully validated signature."
def test_jws_1(): msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} key = SYMKey(key=jwkest.intarr2bin(HMAC_KEY)) _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.to_dict()) res = _jws.sign_compact() _jws2 = JWS(alg="HS256") _jws2.verify_compact(res, keys=[key]) assert _jws2.msg == msg
def test_jws_1(): msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} key = SYMKey(key=jwkest.intarr2bin(HMAC_KEY)) _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.serialize()) res = _jws.sign_compact() _jws2 = JWS(alg="HS256") _jws2.verify_compact(res, keys=[key]) assert _jws2.msg == msg
def test_jws_1(): msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} jwk = SYMKey(key=jwkest.intarr2bin(HMAC_KEY)) _jws = JWS(msg, cty="JWT", alg="HS256", jwk=json.dumps(jwk.to_dict())) res = _jws.sign_compact() _jws2 = JWS(alg="HS256") _jws2.verify_compact(res) assert _jws2.msg == msg
def test_jws_1(): msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} jwk = SYMKey(key=jwkest.intarr2bin(HMAC_KEY)) jwk.serialize() _jws = JWS(msg, cty="JWT", alg="HS256", jwk=json.dumps(jwk.to_dict())) res = _jws.sign_compact() _jws2 = JWS() _jws2.verify_compact(res) assert _jws2.msg == msg
def _verify(self, jws, keys): # type: (str, Sequence[Key]) -> Dict[str, Union[str, Lists[str]]] """ Verify signature of JWS. :param jws: JWS to verify signature of :param keys: possible keys to verify the signature with :return: payload of the JWS """ unpacked = JWS() unpacked.verify_compact(jws, keys=keys) return unpacked
def test_signer_ps256_fail(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS256") _jwt = _jws.sign_compact(keys)[:-5] + 'abcde' _rj = JWS() try: _rj.verify_compact(_jwt, keys) except jwkest.BadSignature: pass else: assert False
def test_signer_ps256_fail(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS256") _jwt = _jws.sign_compact(keys)[:-1] + "a" _rj = JWS() try: _rj.verify_compact(_jwt, keys) except jwkest.BadSignature: pass else: assert False
def validate(self, jwt, iss, aud): header, payload = (json.loads(x) for x in decode_token(jwt)) if 'iss' not in payload or iss != payload['iss']: raise JwtValidatorException('Invalid issuer') if 'aud' not in payload or aud != payload['aud']: raise JwtValidatorException('Invalid audience') if time() > payload['exp']: raise JwtValidatorException('JWT expired!') jws = JWS(alg=header['alg']) # Raises exception when signature is invalid try: jws.verify_compact(jwt, self.jwks) except Exception as e: raise JwtValidatorException(e)
def test_1(): claimset = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} _jws = JWS(claimset, cty="JWT") _jwt = _jws.sign_compact() _jr = JWS() _jr.verify_compact(_jwt) print _jr assert _jr.alg == u'none' assert _jr.msg == {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
def check_jwks(self, entity): # all keys in JWKS has scoped kid assert all(key.kid.startswith(entity.name) for key in entity.jwks[""][0].keys()) _jws = JWS() assert _jws.verify_compact(entity.signed_jwks, keys=[entity.intermediate_key]) assert _jws.jwt.headers["kid"] == entity.intermediate_key.kid
def test_client_secret_jwt(self, client): client.token_endpoint = "https://example.com/token" client.provider_info = { 'issuer': 'https://example.com/', 'token_endpoint': "https://example.com/token" } csj = ClientSecretJWT(client) cis = AccessTokenRequest() csj.construct(cis, algorithm="HS256", authn_endpoint='userinfo') assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] _jwt = JWT().unpack(cas) jso = _jwt.payload() assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert _jwt.headers == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact( cas, [SYMKey(k=b64e(as_bytes(client.client_secret)))]) assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert info['aud'] == [client.provider_info['issuer']]
def assert_registration_req(self, request, internal_response, sign_key_path, base_url, requester_name): split_path = request.path_url.lstrip("/").split("/") assert len(split_path) == 2 jwks = split_path[1] # Verify signature sign_key = RSAKey(key=rsa_load(sign_key_path), use="sig") jws = JWS() jws.verify_compact(jwks, [sign_key]) consent_args = jws.msg assert consent_args["attr"] == internal_response.attributes assert consent_args["redirect_endpoint"] == base_url + "/consent/handle_consent" assert consent_args["requester_name"] == requester_name assert consent_args["locked_attrs"] == [USER_ID_ATTR] assert "id" in consent_args
def jwtValidate(self, token): """ jwt方式解析token :param token: 需要解析的token. :type field: str :returns: 解析成功返回None;解析失败返回错误信息. :rtype: object .. versionadded:: 1.0 """ parts = token.split('.') if len(parts) != 3: raise BadSignature('Invalid JWT. Only JWS supported.') header = json.loads(base64_urldecode(parts[0])) payload = json.loads(base64_urldecode(parts[1])) # 校验 issuer if self.expectedIssuer != payload['iss']: return "Invalid issuer %s, expected %s" % (payload['iss'], self.expectedIssuer) # 校验 client_id if payload["aud"]: if (isinstance(payload["aud"], str) and payload["aud"] != self.clientId) or self.clientId not in payload['aud']: return "Invalid audience %s, expected %s" % (payload['aud'], self.clientId) # 校验过期时间 if int(time.time()) >= int(payload['exp']): return "Token has expired" # 校验生效时间 if int(time.time()) <= int(payload['iat']): return "Token issued in the past" jws = JWS(alg=header['alg']) try: jws.verify_compact(token, self.jwks) return except Exception as e: # 第一次解析异常时,更新jwks信息重新解析 try: self.jwks = self.load_keys() jws.verify_compact(token, self.jwks) return except Exception as e: return 'Invalid token!'
def test_hmac_from_keyrep(): payload = "Please take a moment to register today" symkeys = [k for k in SIGKEYS if k.kty == "oct"] _jws = JWS(payload, alg="HS512") _jwt = _jws.sign_compact(symkeys) _rj = JWS() info = _rj.verify_compact(_jwt, symkeys) assert info == payload
def assert_registration_req(self, request, internal_response, sign_key_path, base_url, requester_name): split_path = request.path_url.lstrip("/").split("/") assert len(split_path) == 2 jwks = split_path[1] # Verify signature sign_key = RSAKey(key=rsa_load(sign_key_path), use="sig") jws = JWS() jws.verify_compact(jwks, [sign_key]) consent_args = jws.msg assert consent_args["attr"] == internal_response.attributes assert consent_args[ "redirect_endpoint"] == base_url + "/consent/handle_consent" assert consent_args["requester_name"] == requester_name assert consent_args["locked_attrs"] == [USER_ID_ATTR] assert "id" in consent_args
def test_hmac_512(): payload = "Please take a moment to register today" keys = [SYM_key(key="My hollow echo")] _jws = JWS(payload, alg="HS256") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_hmac_512(): payload = "Please take a moment to register today" keys = [SYMKey(key=b'My hollow echo', alg="HS512")] _jws = JWS(payload, alg="HS512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_hmac_from_keyrep(): payload = "Please take a moment to register today" symkeys = [k for k in SIGKEYS if k.kty == "oct"] _jws = JWS(payload, alg="HS512") _jwt = _jws.sign_compact(symkeys) _rj = JWS() info = _rj.verify_compact(_jwt, symkeys) assert info == payload
def test_1(): claimset = { "iss": "joe", "exp": 1300819380, "http://example.com/is_root": True } _jws = JWS(claimset, cty="JWT") _jwt = _jws.sign_compact() _jr = JWS() _jr.verify_compact(_jwt) print _jr assert _jr.alg == u'none' assert _jr.msg == { "iss": "joe", "exp": 1300819380, "http://example.com/is_root": True }
def test_signer_ps384(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS384") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_es384(): payload = "Please take a moment to register today" _key = ECKey().load_key(P384) keys = [_key] _jws = JWS(payload, alg="ES384") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_ps384(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS384") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_es384(): payload = "Please take a moment to register today" _key = ECKey().load_key(P384) keys = [_key] _jws = JWS(payload, alg="ES384") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_rs512(): payload = "Please take a moment to register today" keys = [RSA_key(key=rsa_load(KEY))] keys[0]._keytype = "private" _jws = JWS(payload, alg="RS512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_es512(): payload = "Please take a moment to register today" _key = ECKey().load_key(P521) keys = [_key] #keys[0]._keytype = "private" _jws = JWS(payload, alg="ES512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_ps512(): payload = "Please take a moment to register today" # Key has to be big enough > 512+512+2 keys = [RSAKey(key=import_rsa_key_from_file("./size2048.key"))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def verify_signature_JWT(self, jwt): symkeys = [k for k in self.SIGKEYS if k.alg == "RS256"] _rj = JWS() info = _rj.verify_compact(jwt, symkeys) decoded_json = self.decode_JWT(jwt) if info == decoded_json: return True else: return False
def test_signer_es512(): payload = "Please take a moment to register today" _key = ECKey().load_key(P521) keys = [_key] #keys[0]._keytype = "private" _jws = JWS(payload, alg="ES512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_ps512(): payload = "Please take a moment to register today" # Key has to be big enough > 512+512+2 keys = [RSAKey(key=import_rsa_key_from_file(full_path("./size2048.key")))] #keys[0]._keytype = "private" _jws = JWS(payload, alg="PS521") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_1(): claimset = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} _jws = JWS(claimset, cty="JWT") _jwt = _jws.sign_compact() _jr = JWS() _msg = _jr.verify_compact(_jwt, allow_none=True) print(_jr) assert _jr.jwt.headers["alg"] == "none" assert _msg == claimset
def test_1(): claimset = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} _jws = JWS(claimset, cty="JWT") _jwt = _jws.sign_compact() _jr = JWS() _msg = _jr.verify_compact(_jwt, allow_none=True) print(_jr) assert _jr.jwt.headers["alg"] == 'none' assert _msg == claimset
def test_sign_json_hs256(): payload = "Please take a moment to register today" keys = [SYMKey(key=jwkest.intarr2bin(HMAC_KEY))] _jws = JWS(payload, alg="HS256") _sig = {'alg': 'HS256'} _jwt = _jws.sign_json(per_signature_head=[_sig], keys=keys, alg='HS256') _jwt_sig = "%s.%s.%s" % (_jwt['signatures'][0]['header'], b64e(_jwt['payload']), _jwt['signatures'][0]['signature']) info = _jws.verify_compact(_jwt_sig, keys) assert info == payload
def test_signer_es512(): payload = "Please take a moment to register today" _key = ECKey(crv="P-521", x="AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk", y="ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2", d="AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C") keys = [_key] #keys[0]._keytype = "private" _jws = JWS(payload, alg="ES512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_sign_json_hs256(): payload = "Please take a moment to register today" keys = [SYMKey(key=jwkest.intarr2bin(HMAC_KEY))] _jws = JWS(payload, alg="HS256") _sig = { 'alg': 'HS256' } _jwt = _jws.sign_json(per_signature_head=[_sig], keys=keys, alg='HS256') _jwt_sig = "%s.%s.%s" % ( _jwt['signatures'][0]['header'], b64e(_jwt['payload']), _jwt['signatures'][0]['signature'] ) info = _jws.verify_compact(_jwt_sig, keys) assert info == payload
def verify_poet(my_jws, my_jwk_dict): # load the Signed JWT (JWS) my_jws = my_jws.rstrip().lstrip() signed_token = JWS(my_jws) # load the JWK rsak = RSAKey(**my_jwk_dict) try: vt = signed_token.verify_compact(signed_token.msg, keys=[rsak]) retval = vt except BadSignature: retval = {"error": "The signature did not match"} except: retval = {"error": str(sys.exc_info())} return retval
def test_rs256_rm_signature(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] # keys[0]._keytype = "private" _jws = JWS(payload, alg="RS256") _jwt = _jws.sign_compact(keys) p = _jwt.split('.') _jwt = '.'.join(p[:-1]) _rj = JWS() try: _ = _rj.verify_compact(_jwt, keys) except jwkest.WrongNumberOfParts: pass else: assert False
def test_rs256_rm_signature(): payload = "Please take a moment to register today" keys = [RSAKey(key=import_rsa_key_from_file(KEY))] # keys[0]._keytype = "private" _jws = JWS(payload, alg="RS256") _jwt = _jws.sign_compact(keys) p = _jwt.split('.') _jwt = '.'.join(p[:-1]) _rj = JWS() try: _ = _rj.verify_compact(_jwt, keys) except jwkest.WrongNumberOfParts: pass else: assert False
def test_signer_protected_headers(): payload = "Please take a moment to register today" _key = ECKey().load_key(P256) keys = [_key] _jws = JWS(payload, alg="ES256") protected = dict(header1=u"header1 is protected", header2="header2 is protected too", a=1) _jwt = _jws.sign_compact(keys, protected=protected) exp_protected = protected.copy() exp_protected["alg"] = "ES256" enc_header, enc_payload, sig = _jwt.split(".") assert json.loads(b64d(enc_header.encode("utf-8")).decode("utf-8")) == exp_protected assert b64d(enc_payload.encode("utf-8")).decode("utf-8") == payload _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_protected_headers(): payload = "Please take a moment to register today" _key = ECKey().load_key(P256) keys = [_key] _jws = JWS(payload, alg="ES256") protected = dict(header1=u"header1 is protected", header2="header2 is protected too", a=1) _jwt = _jws.sign_compact(keys, protected=protected) exp_protected = protected.copy() exp_protected['alg'] = 'ES256' enc_header, enc_payload, sig = _jwt.split('.') assert json.loads(b64d(enc_header.encode("utf-8")).decode("utf-8")) == exp_protected assert b64d(enc_payload.encode("utf-8")).decode("utf-8") == payload _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_signer_es512(): payload = "Please take a moment to register today" _key = ECKey( crv="P-521", x= "AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk", y= "ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2", d="AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C" ) _key.deserialize() keys = [_key] #keys[0]._keytype = "private" _jws = JWS(payload, alg="ES512") _jwt = _jws.sign_compact(keys) _rj = JWS() info = _rj.verify_compact(_jwt, keys) assert info == payload
def test_client_secret_jwt(self, client): client.token_endpoint = "https://example.com/token" csj = ClientSecretJWT(client) cis = AccessTokenRequest() http_args = csj.construct(cis, algorithm="HS256") assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] _jwt = JWT().unpack(cas) jso = _jwt.payload() assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert _jwt.headers == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact(cas, [SYMKey(key=client.client_secret)]) assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
def test_client_secret_jwt(self, client): client.token_endpoint = "https://example.com/token" csj = ClientSecretJWT(client) cis = AccessTokenRequest() http_args = csj.construct(cis, algorithm="HS256") assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] _jwt = JWT().unpack(cas) jso = _jwt.payload() assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert _jwt.headers == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact(cas, [SYMKey(key=client.client_secret)]) assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
def verify_poet_via_url(my_jws): # load the Signed JWT (JWS) my_jws = my_jws.rstrip().lstrip() signed_token = JWS(my_jws) # create aplain old JWT so we can fish out the 'iss' t = JWT() unpacked = t.unpack(token=my_jws) payload = unpacked.payload() if "iss" not in payload: print("Missing 'iss' claim in the JWS payload.") exit(1) else: iss = payload['iss'] # Fetch the public key from iss url = "https://%s/.well-known/poet.jwk" % (iss) r = requests.get(url) if r.status_code != 200: print("The key could not be fetched.") exit(1) # load the JWK into an RSA Key structure rsak = RSAKey(**r.json()) try: vt = signed_token.verify_compact(signed_token.msg, keys=[rsak]) retval = vt except BadSignature: retval = {"error": "The signature did not match"} except NoSuitableSigningKeys: retval = {"error": str(sys.exc_info()[1])} except DeSerializationNotPossible: retval = {"error": str(sys.exc_info()[1])} except: retval = {"error": str(sys.exc_info())} return retval
def test_client_secret_jwt(self, client): client.token_endpoint = "https://example.com/token" client.provider_info = {'issuer': 'https://example.com/', 'token_endpoint': "https://example.com/token"} csj = ClientSecretJWT(client) cis = AccessTokenRequest() csj.construct(cis, algorithm="HS256", authn_endpoint='userinfo') assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] _jwt = JWT().unpack(cas) jso = _jwt.payload() assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert _jwt.headers == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact( cas, [SYMKey(k=b64e(as_bytes(client.client_secret)))]) assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) assert info['aud'] == [client.provider_info['issuer']]
def test_client_secret_jwt(): cli = Client("Foo") cli.token_endpoint = "https://example.com/token" cli.client_secret = "foobar" csj = ClientSecretJWT(cli) cis = AccessTokenRequest() http_args = csj.construct(cis, algorithm="HS256") print http_args assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] header, claim, crypto, header_b64, claim_b64 = jwkest.unpack(cas) jso = json.loads(claim) assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) print header assert header == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact(cas, [SYMKey(key=cli.client_secret)]) _dict = json.loads(info) assert _eq(_dict.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
def validate(self, jwt): parts = jwt.split('.') if len(parts) != 3: print 'Invalid JWT. Only JWS supported.' return {"active": False} try: header = json.loads(base64_urldecode(parts[0])) payload = json.loads(base64_urldecode(parts[1])) except Exception as e: print "Invalid JWT, format not json" return {"active": False} if self.iss != payload['iss']: print "Invalid issuer %s, expected %s" % (payload['iss'], self.iss) return {"active": False} if 'aud' not in payload: print "Invalid audience, no audience in payload" return {"active": False} aud = payload['aud'] if self.aud not in aud: print "Invalid audience %s, expected %s" % (aud, self.aud) return {"active": False} if 'alg' not in header: print "Missing algorithm in header" return {"active": False} if header['alg'] not in self.supported_algoritms: print "Unsupported algorithm in header %s" % (header['alg']) return {"active": False} jws = JWS(alg=header['alg']) # Raises exception when signature is invalid try: jws.verify_compact(jwt, self.jwks) except Exception as e: print "Exception validating signature" return {'active': False} print "Successfully validated signature." if 'exp' not in payload: print "No expiration in body, invalid token" return {"active": False} if 'sub' not in payload: print "No subject in body, invalid token" return {"active": False} # Could be an empty scope, which may be allowed, so replace with empty string if not found if 'scope' not in payload: scope = "" else: scope = payload['scope'] exp = payload['exp'] d = datetime.utcnow() now = calendar.timegm(d.utctimetuple()) if now >= exp: return {"active": False} else: return {"subject": payload['sub'], "scope": scope, "active": True}
# $ ssh-keygen -t rsa -b 4096 # and provide the foo filename with requested. # # Now a JWS can be created as follow: # - retrieve the rsa key (the example below will also print it in the JWK section) # - use the JWS object to create the token specifying the algorithm to be used for signing # - call the method sign_compact providing an array of keys (eventually containing 1 key only) to be used for signing # - the example belows shows the content of the JWT, by printing it # - the signature can be verified with the method verify_compact (of course providing the same keys used for signing) payload = {"iss": "jow", "exp": 1300819380, "http://example.com/is_root": True} keys = [RSAKey(key=import_rsa_key_from_file("foo"))] jws = JWS(payload, alg="RS512").sign_compact(keys) print "jwt signed:", jws print ######################################## jwt_received = JWT() jwt_received.unpack(jws) print "jwt headers:", jwt_received.headers print "jwt part 1:", jwt_received.part[1] print _rj = JWS() info = _rj.verify_compact(jws, keys) print "Verified info:", info
def verify(msg, keys): _jws = JWS() return _jws.verify_compact(msg, keys)
def check_intermediate_key(self, entity): assert entity.intermediate_key.kid.startswith(entity.name) # has scoped kid _jws = JWS() assert _jws.verify_compact(entity.signed_intermediate_key, keys=[entity.root_key]) assert _jws.jwt.headers["kid"] == entity.root_key.kid
def from_jwt(self, txt, key=None, verify=True, keyjar=None, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :return: A class instance """ if key is None and keyjar is not None: key = keyjar.get_verify_key(owner="") elif key is None: key = {} header = json.loads(b64d(str(txt.split(".")[0]))) logger.debug("header: %s" % (header,)) try: htype = header["typ"] except KeyError: htype = None jso = None if htype == "JWE" or ("alg" in header and "enc" in header): # encrypted if keyjar: dkeys = keyjar.get_decrypt_key(owner="") else: dkeys = {} txt = JWE().decrypt(txt, dkeys, "private") try: jso = json.loads(txt) except Exception: pass # assume htype == 'JWS' _jws = JWS() if not jso: try: jso = jwkest.unpack(txt)[1] try: self._add_key(keyjar, kwargs["opponent_id"], key) except KeyError: pass if isinstance(jso, basestring): jso = json.loads(jso) if verify: if keyjar: for ent in ["iss", "aud", "client_id"]: if ent not in jso: continue if ent == "aud": for _e in jso[ent]: self._add_key(keyjar, _e, key) else: self._add_key(keyjar, jso[ent], key) _jws.verify_compact(txt, key) except Exception: raise return self.from_dict(jso)
def from_jwt(self, txt, key=None, verify=True, keyjar=None, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :return: A class instance """ if key is None and keyjar is not None: key = keyjar.get_verify_key(owner="") elif key is None: key = {} header = json.loads(b64d(str(txt.split(".")[0]))) logger.debug("header: %s" % (header, )) try: htype = header["typ"] except KeyError: htype = None try: _kid = header["kid"] except KeyError: _kid = "" jso = None if htype == "JWE" or ("alg" in header and "enc" in header): # encrypted if keyjar: dkeys = keyjar.get_decrypt_key(owner="") else: dkeys = {} txt = JWE().decrypt(txt, dkeys) try: jso = json.loads(txt) except Exception: pass # assume htype == 'JWS' _jws = JWS() if not jso: try: jso = jwkest.unpack(txt)[1] if isinstance(jso, basestring): jso = json.loads(jso) if keyjar: if "jku" in header: if not keyjar.find(header["jku"], jso["iss"]): # This is really questionable try: if kwargs["trusting"]: keyjar.add(jso["iss"], header["jku"]) except KeyError: pass if _kid: try: _key = keyjar.get_key_by_kid(_kid, jso["iss"]) if _key: key.append(_key) except KeyError: pass try: self._add_key(keyjar, kwargs["opponent_id"], key) except KeyError: pass if verify: if keyjar: for ent in ["iss", "aud", "client_id"]: if ent not in jso: continue if ent == "aud": # list or basestring if isinstance(jso["aud"], basestring): _aud = [jso["aud"]] else: _aud = jso["aud"] for _e in _aud: self._add_key(keyjar, _e, key) else: self._add_key(keyjar, jso[ent], key) if "alg" in header and header["alg"] != "none": if not key: raise MissingSigningKey("alg=%s" % header["alg"]) _jws.verify_compact(txt, key) except Exception: raise return self.from_dict(jso)
def verify(msg, keys, allow_none=False, sigalg=None): _jws = JWS() return _jws.verify_compact(msg, keys, allow_none, sigalg)
print(70 * "-") print('Received primary key') print(70 * "-") print_lines( json.dumps(_sost['signing_key'], sort_keys=True, indent=2, separators=(',', ': '))) # ------------------------------ # get the intermediate key # ------------------------------ _jws = factory(rr['signing_key']) _keys = A_keyjar.get_issuer_keys('') intermediate_keys = _jws.verify_compact(rr['signing_key'], _keys) intermediate_keyjar = KeyJar() intermediate_keyjar.add_kb('', KeyBundle(intermediate_keys['keys'])) print(70 * "-") print('Received intermediate keys') print(70 * "-") print_lines( json.dumps(intermediate_keys, sort_keys=True, indent=2, separators=(',', ': '))) # ------------------------------ # Verify metadata signature # ------------------------------
def verify(msg, keys): _jws = JWS() return _jws.verify_compact(msg, keys)