本文整理汇总了Python中jwt.get_unverified_header方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.get_unverified_header方法的具体用法?Python jwt.get_unverified_header怎么用?Python jwt.get_unverified_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.get_unverified_header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _validate_iap_jwt
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def _validate_iap_jwt(iap_jwt):
"""Validate JWT assertion."""
project_id = utils.get_application_id()
expected_audience = '/projects/{}/apps/{}'.format(
_project_number_from_id(project_id), project_id)
try:
key_id = jwt.get_unverified_header(iap_jwt).get('kid')
if not key_id:
raise AuthError('No key ID.')
key = _get_iap_key(key_id)
decoded_jwt = jwt.decode(
iap_jwt,
key,
algorithms=['ES256'],
issuer='https://cloud.google.com/iap',
audience=expected_audience)
return decoded_jwt['email']
except (jwt.exceptions.InvalidTokenError,
requests.exceptions.RequestException) as e:
raise AuthError('JWT assertion decode error: ' + str(e))
示例2: test_verify_jwt_with_none_algorithm
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def test_verify_jwt_with_none_algorithm(self):
""" tests that verify_jwt does not accept jwt that use the none
algorithm.
"""
verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
private_key_ret = atlassian_jwt_auth.key.StaticPrivateKeyRetriever(
self._example_key_id, self._private_key_pem.decode())
jwt_signer = NoneAlgorithmJwtAuthSigner(
issuer=self._example_issuer,
private_key_retriever=private_key_ret,
)
for algorithm in ['none', 'None', 'nOne', 'nonE', 'NONE']:
jwt_token = jwt_signer.generate_jwt(
self._example_aud, alg_header=algorithm)
jwt_headers = jwt.get_unverified_header(jwt_token)
self.assertEqual(jwt_headers['alg'], algorithm)
with self.assertRaises(jwt.exceptions.InvalidAlgorithmError):
verifier.verify_jwt(jwt_token, self._example_aud)
示例3: verify_signature
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def verify_signature(self, token):
try:
header = jwt.get_unverified_header(token)
except jwt.exceptions.DecodeError:
raise TokenValidationError("ID token could not be decoded.")
alg = header.get('alg', None)
if alg != self._algorithm:
raise TokenValidationError(
'Signature algorithm of "{}" is not supported. Expected the ID token '
'to be signed with "{}"'.format(alg, self._algorithm))
kid = header.get('kid', None)
secret_or_certificate = self._fetch_key(key_id=kid)
try:
decoded = jwt.decode(jwt=token, key=secret_or_certificate,
algorithms=[self._algorithm], options=self.DISABLE_JWT_CHECKS)
except jwt.exceptions.InvalidSignatureError:
raise TokenValidationError("Invalid token signature.")
return decoded
示例4: authorize
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def authorize(self, request, uid=None):
token = self._get_raw_token(request)
issuer_info = self._get_issuer_info()
unverified_headers = jwt.get_unverified_header(token)
key_id = unverified_headers.get('kid', None)
if key_id is None:
raise UnauthorizedException("Missing key id in token")
jwks_uri = issuer_info.get('jwks_uri')
if jwks_uri is None:
raise UnauthorizedException("Missing JWKS URI in config")
key, algo = self._get_signing_key(jwks_uri, key_id)
try:
claims = jwt.decode(token, key, algorithms=algo,
issuer=issuer_info['issuer'],
audience=self.config['audience'])
except Exception as e:
raise UnauthorizedException('Invalid access token: %s' % e)
if claims['preferred_username'] == self.config.get('admin_username',
'admin'):
return 'admin'
if uid and uid == claims['preferred_username']:
return uid
if uid and uid != claims['preferred_username']:
raise UnauthorizedException("Only the admin ")
raise UnauthorizedException('unauthorized')
示例5: _get_public_key
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def _get_public_key(self, token):
try:
headers = jwt.get_unverified_header(token)
except jwt.DecodeError as exc:
raise TokenError(str(exc))
if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False):
cache_key = "django_cognito_jwt:%s" % headers["kid"]
jwk_data = cache.get(cache_key)
if not jwk_data:
jwk_data = self._json_web_keys.get(headers["kid"])
timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300)
cache.set(cache_key, jwk_data, timeout=timeout)
else:
jwk_data = self._json_web_keys.get(headers["kid"])
if jwk_data:
return RSAAlgorithm.from_jwk(jwk_data)
示例6: main
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def main():
if len(sys.argv) <= 1:
sys.stdout.write("\t-::: jwt-decoder.py :::-\n")
sys.stdout.write("# Returns the decoded value of a JWT.\n")
sys.stdout.write("\nUsage: %s [jwt-token]\n" % (sys.argv[0]))
sys.stdout.flush()
exit(0)
jwt_token = sys.argv[1]
jwt_token_header = jwt.get_unverified_header(jwt_token)
jwt_token_value = jwt.decode(jwt_token, verify=False)
sys.stdout.write("\n\n")
sys.stdout.write("[#] JWT Header:\n%s\n\n" %
(json.dumps(jwt_token_header)))
sys.stdout.write("[#] JWT Value:\n%s\n" % (json.dumps(jwt_token_value)))
sys.stdout.flush()
exit(0)
示例7: metadata_toc
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def metadata_toc(self):
if self._metadata_toc is None:
res = requests.get(self.mds_url)
res.raise_for_status()
jwt_header = jwt.get_unverified_header(res.content)
assert jwt_header["alg"] == "ES256"
cert = x509.load_der_x509_certificate(jwt_header["x5c"][0].encode(),
cryptography.hazmat.backends.default_backend())
self._metadata_toc = jwt.decode(res.content, key=cert.public_key(), algorithms=["ES256"])
return self._metadata_toc
示例8: _validate_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def _validate_token(
self, jwt_token: str, channel_id: str, required_endorsements: List[str] = None
) -> ClaimsIdentity:
required_endorsements = required_endorsements or []
headers = jwt.get_unverified_header(jwt_token)
# Update the signing tokens from the last refresh
key_id = headers.get("kid", None)
metadata = await self.open_id_metadata.get(key_id)
if key_id and metadata.endorsements:
# Verify that channelId is included in endorsements
if not EndorsementsValidator.validate(channel_id, metadata.endorsements):
raise Exception("Could not validate endorsement key")
# Verify that additional endorsements are satisfied.
# If no additional endorsements are expected, the requirement is satisfied as well
for endorsement in required_endorsements:
if not EndorsementsValidator.validate(
endorsement, metadata.endorsements
):
raise Exception("Could not validate endorsement key")
if headers.get("alg", None) not in self.validation_parameters.algorithms:
raise Exception("Token signing algorithm not in allowed list")
options = {
"verify_aud": False,
"verify_exp": not self.validation_parameters.ignore_expiration,
}
decoded_payload = jwt.decode(
jwt_token,
metadata.public_key,
leeway=self.validation_parameters.clock_tolerance,
options=options,
)
claims = ClaimsIdentity(decoded_payload, True)
return claims
示例9: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def validate(ssd):
try:
ssd_header = jwt.get_unverified_header(ssd)
jwt.decode(ssd, SFSsd.ret_ssd_pub_key(ssd_header['ssd_iss']),
algorithm='RS512')
except Exception as ex:
logger.debug("Error while validating SSD Token", ex)
return False
return True
示例10: process_key_update_directive
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def process_key_update_directive(issuer, key_upd_dir_enc):
"""Parses the jwt token as key update directive.
If the key version in directive < internal key versio do nothing as the internal key is already latest.
Otherwise update in memory pub key corresponding to the issuer in the directive.
Expected Format:
Payload:
{
“keyVer” :
“pubKeyTyp” :
“pubKey” :
}
"""
logger.debug(
"Received an OCSP Key Update Server Side Directive from Issuer - ",
issuer)
jwt_ssd_header = jwt.get_unverified_header(key_upd_dir_enc)
ssd_issuer = jwt_ssd_header['ssd_iss']
# Use the in memory public key corresponding to 'issuer'
# for JWT signature validation.
jwt_ssd_decoded = jwt.decode(key_upd_dir_enc,
SnowflakeOCSP.SSD.ret_ssd_pub_key(
ssd_issuer), algorithm='RS512')
ssd_pub_key_ver = float(jwt_ssd_decoded['keyVer'])
ssd_pub_key_new = jwt_ssd_decoded['pubKey']
"""
Check for consistency in issuer name
Check if the key version of the new key is greater than
existing pub key being used.
If both checks pass update key.
"""
if ssd_issuer == issuer and ssd_pub_key_ver > SFSsd.ret_ssd_pub_key_ver(
ssd_issuer):
SnowflakeOCSP.SSD.update_pub_key(ssd_issuer, ssd_pub_key_ver,
ssd_pub_key_new)
示例11: get_unverified_jwt_headers
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def get_unverified_jwt_headers(encoded_token):
"""
Returns the Headers of an encoded JWT without verifying the actual signature of JWT.
Note: The signature is not verified so the header parameters
should not be fully trusted until signature verification is complete
:param encoded_token: The encoded JWT to get the Header from.
:return: JWT header parameters as python dict()
"""
return jwt.get_unverified_header(encoded_token)
示例12: decode_id_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def decode_id_token(self, id_token: str) -> Dict[str, Any]:
'''Decode and validate JWT token from Apple and return payload including user data.
We override this method from upstream python-social-auth, for two reasons:
* To improve error handling (correctly raising AuthFailed; see comment below).
* To facilitate this to support the native flow, where
the Apple-generated id_token is signed for "Bundle ID"
audience instead of "Services ID".
It is likely that small upstream tweaks could make it possible
to make this function a thin wrapper around the upstream
method; we may want to submit a PR to achieve that.
'''
if self.is_native_flow():
audience = self.setting("BUNDLE_ID")
else:
audience = self.setting("SERVICES_ID")
try:
kid = jwt.get_unverified_header(id_token).get('kid')
public_key = RSAAlgorithm.from_jwk(self.get_apple_jwk(kid))
decoded = jwt.decode(id_token, key=public_key,
audience=audience, algorithm="RS256")
except PyJWTError:
# Changed from upstream python-social-auth to raise
# AuthFailed, which is more appropriate than upstream's
# AuthCanceled, for this case.
raise AuthFailed(self, "Token validation failed")
return decoded
示例13: _get_key_id_from_jwt_header
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def _get_key_id_from_jwt_header(a_jwt):
""" returns the key identifier from a jwt header. """
header = jwt.get_unverified_header(a_jwt)
return KeyIdentifier(header['kid'])
示例14: jwt_decode
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def jwt_decode(self):
"""Decode a JWT token. Does not verify
Returns:
Chepy: The Chepy object.
"""
self.state = {
"payload": jwt.decode(self._convert_to_str(), verify=False),
"header": jwt.get_unverified_header(self._convert_to_str()),
}
return self
示例15: jwt_bruteforce
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import get_unverified_header [as 别名]
def jwt_bruteforce(
self, wordlist: str, b64_encode: bool = False, algorithm: list = ["HS256"]
):
"""Brute force JWT token secret
This method will use the provided wordlist to try and bruteforce the
verification.
Args:
wordlist (str): Required. Path to a wordlist
b64_encode (bool, optional): Encoded the words in base64. Defaults to False.
algorithm (list, optional): Array of valid algorithms. Defaults to ["HS256"].
Returns:
Chepy: The Chepy object.
"""
with open(pathlib.Path(wordlist).expanduser().absolute()) as words:
for word in words:
try:
word = word.strip()
if b64_encode: # pragma: no cover
word = base64.b64encode(word)
j = jwt.decode(self._convert_to_str(), word, algorithms=algorithm)
self.state = {
"paylod": j,
"header": jwt.get_unverified_header(self._convert_to_str()),
"secret": word,
}
return self
except jwt.InvalidSignatureError:
continue
else: # pragma: no cover
return self