Python jwt.algorithms.RSAAlgorithm.from_jwk() Examples
The following are 9
code examples of jwt.algorithms.RSAAlgorithm.from_jwk().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jwt.algorithms.RSAAlgorithm
, or try the search function
.
Example #1
Source File: validator.py From django-cognito-jwt with MIT License | 6 votes |
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)
Example #2
Source File: jwt_token_extractor.py From botbuilder-python with MIT License | 5 votes |
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)
Example #3
Source File: backends.py From zulip with Apache License 2.0 | 5 votes |
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
Example #4
Source File: keycloak_authentication.py From tfrs with Apache License 2.0 | 5 votes |
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
Example #5
Source File: synapse_oauth2.py From fence with Apache License 2.0 | 5 votes |
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
Example #6
Source File: keycloak.py From vitrage with Apache License 2.0 | 5 votes |
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
Example #7
Source File: utils.py From django-cognito-jwt with MIT License | 5 votes |
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})
Example #8
Source File: azuread_b2c.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
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 )
Example #9
Source File: client.py From django_microsoft_auth with MIT License | 4 votes |
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