How to use the jwt.algorithms.RSAAlgorithm.from_jwk function in jwt

To help you get started, we’ve selected a few jwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jpadilla / pyjwt / tests / keys / __init__.py View on Github external
def load_rsa_key():
        with open(os.path.join(BASE_PATH, "jwk_rsa_key.json"), "r") as infile:
            return RSAAlgorithm.from_jwk(infile.read())
github pingidentity / pingone-customers-sample-oidc / python / services / auth.py View on Github external
def validate_token(self, token, verify_nonce=True):
        """
        Validate JWT token
        :param token: JWT token
        :param verify_nonce:
        :return:
        """

        id_token_parts = token.split('.')
        if len(id_token_parts) < 3:
            abort(403, 'Invalid token: unable to split the token content. ')

        keys = {k['kid']: jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(k)) for k in self.get_jwk()['keys']}
        unverified_header = jwt.get_unverified_header(token)
        key_id = unverified_header['kid']
        algorithm = unverified_header['alg']
        public_key = keys[key_id]
        # Check and raise an error if the token verification/validation has some errors(i.e is expired, invalid audience).
        decoded_token = jwt.decode(token, public_key, algorithms=algorithm,
                                   issuer=self.issuer, audience=self.client_id,
                                   require_exp=True, require_iat=True)

        known_nonce = session.get(AUTH_NONCE_KEY)
        stated_nonce = decoded_token[NONCE]
        if verify_nonce and (not known_nonce or not stated_nonce or stated_nonce != known_nonce):
            abort(403, "Invalid nonce value. ")

        return decoded_token
github getredash / redash / redash / authentication / jwt_auth.py View on Github external
def get_public_keys(url):
    """
    Returns:
        List of RSA public keys usable by PyJWT.
    """
    key_cache = get_public_keys.key_cache
    if url in key_cache:
        return key_cache[url]
    else:
        r = requests.get(url)
        r.raise_for_status()
        data = r.json()
        if 'keys' in data:
            public_keys = []
            for key_dict in data['keys']:
                public_key = jwt.algorithms.RSAAlgorithm.from_jwk(simplejson.dumps(key_dict))
                public_keys.append(public_key)

            get_public_keys.key_cache[url] = public_keys
            return public_keys
        else:
            get_public_keys.key_cache[url] = data
            return data
github openstack / vitrage / vitrage / middleware / keycloak.py View on Github external
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
github python-social-auth / social-core / social_core / backends / apple.py View on Github external
def decode_id_token(self, id_token):
        """
        Decode and validate JWT token from apple and return payload including
        user data.
        """
        if not id_token:
            raise AuthCanceled("Missing id_token parameter")

        kid = jwt.get_unverified_header(id_token).get('kid')
        public_key = RSAAlgorithm.from_jwk(self.get_apple_jwk(kid))
        try:
            decoded = jwt.decode(
                id_token,
                key=public_key,
                audience=self.get_audience(),
                algorithm="RS256",
            )
        except PyJWTError:
            raise AuthCanceled("Token validation failed")

        return decoded
github microsoft / botbuilder-python / libraries / botframework-connector / botframework / connector / auth / jwt_token_extractor.py View on Github external
def _find(self, key_id: str):
        if not self.keys:
            return None
        key = next(x for x in self.keys if x["kid"] == key_id)
        public_key = RSAAlgorithm.from_jwk(json.dumps(key))
        endorsements = key.get("endorsements", [])
        return _OpenIdConfig(public_key, endorsements)
github AngellusMortis / django_microsoft_auth / microsoft_auth / client.py View on Github external
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