本文整理匯總了Python中jwt.algorithms.RSAAlgorithm.from_jwk方法的典型用法代碼示例。如果您正苦於以下問題:Python RSAAlgorithm.from_jwk方法的具體用法?Python RSAAlgorithm.from_jwk怎麽用?Python RSAAlgorithm.from_jwk使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jwt.algorithms.RSAAlgorithm
的用法示例。
在下文中一共展示了RSAAlgorithm.from_jwk方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_public_key
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [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)
示例2: _find
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def _find(self, key_id: str):
if not self.keys:
return None
key = [x for x in self.keys if x["kid"] == key_id][0]
public_key = RSAAlgorithm.from_jwk(json.dumps(key))
endorsements = key.get("endorsements", [])
return _OpenIdConfig(public_key, endorsements)
示例3: decode_id_token
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [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
示例4: _get_keys
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def _get_keys(self):
"""
Assemble a list of valid signing public keys we use to verify the token
"""
decoded_keys = {}
# We have a test key loaded
if settings.KEYCLOAK['RS256_KEY'] is not None:
decoded_keys['imported'] = settings.KEYCLOAK['RS256_KEY']
if not settings.KEYCLOAK['DOWNLOAD_CERTS']:
return decoded_keys
keys = cache.get('verification_keys')
if keys is None:
# Cache miss. Download a key directly from Keycloak
response = requests.get(settings.KEYCLOAK['CERTS_URL'], timeout=5)
if not response:
raise RuntimeError('keys not available from {}'.format(
settings.KEYCLOAK['CERTS_URL']))
keys = response.json()
cache.set('verification_keys', keys, 600)
decoded_keys = {}
for key in keys['keys']:
if key['alg'] in ['RS256', 'RS384', 'RS512']:
decoded_keys[key['kid']] = RSAAlgorithm.from_jwk(
json.dumps(key)
).public_bytes(
format=serialization.PublicFormat.SubjectPublicKeyInfo,
encoding=serialization.Encoding.PEM
).decode('utf-8')
return decoded_keys
示例5: load_key
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def load_key(self, jwks_endpoint):
"""
A custom method to load a Synapse "RS256" key.
Synapse is not providing standard JWK keys:
* kty is RS256 not RSA
* e and n are not base64-encoded
Synapse is updating their JWKS document to align it with conventions,
so above logic could be abandoned in the future.
"""
for key in self.get_jwt_keys(jwks_endpoint):
# For new Synapse JWKS doc, which is modified with conventions
if key["kty"] == "RSA":
return "RS256", RSAAlgorithm.from_jwk(json.dumps(key))
# For old Synapse JWKS odc, kept for backward compability
# TODO: remove after tested with new Synapse JWKS doc
# and Synapse has deployed their changes
elif key["kty"] == "RS256":
key["kty"] = "RSA"
for field in ["e", "n"]:
if key[field].isdigit():
key[field] = to_base64url_uint(int(key[field])).decode()
return "RS256", RSAAlgorithm.from_jwk(json.dumps(key))
return None, None
示例6: get_public_key
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def get_public_key(self, realm_name):
keycloak_key_url = self.auth_url + self.public_cert_url % realm_name
response_json = self.send_request_to_auth_server(keycloak_key_url)
public_key = RSAAlgorithm.from_jwk(
json.dumps(response_json["keys"][0]))
return public_key
示例7: create_jwt_token
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def create_jwt_token(private_key, payload):
key = json.dumps(private_key)
key_id = private_key["kid"]
secret = RSAAlgorithm.from_jwk(key)
return jwt.encode(payload, secret, algorithm="RS256", headers={"kid": key_id})
示例8: jwt_key_to_pem
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def jwt_key_to_pem(self, key_json_dict):
"""
Builds a PEM formatted key string from a JWT public key dict.
"""
pub_key = RSAAlgorithm.from_jwk(json.dumps(key_json_dict))
return pub_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
示例9: get_claims
# 需要導入模塊: from jwt.algorithms import RSAAlgorithm [as 別名]
# 或者: from jwt.algorithms.RSAAlgorithm import from_jwk [as 別名]
def get_claims(self, allow_refresh=True):
if self.token is None:
return None
token = self.token["id_token"].encode("utf8")
kid = jwt.get_unverified_header(token)["kid"]
jwk = None
public_key = None
for key in self.jwks:
if kid == key["kid"]:
jwk = key
break
if jwk is None:
if allow_refresh:
logger.warn(
"could not find public key for id_token, "
"refreshing OIDC config"
)
cache.delete(CACHE_KEY_JWKS)
cache.delete(CACHE_KEY_OPENID)
return self.get_claims(allow_refresh=False)
else:
logger.warn("could not find public key for id_token")
return None
public_key = RSAAlgorithm.from_jwk(json.dumps(jwk))
try:
claims = jwt.decode(
token,
public_key,
algoithm="RS256",
audience=self.config.MICROSOFT_AUTH_CLIENT_ID,
)
except jwt.PyJWTError as e:
logger.warn("could verify id_token sig: {}".format(e))
return None
return claims