当前位置: 首页>>代码示例>>Python>>正文


Python jwt.get_unverified_header方法代码示例

本文整理汇总了Python中jose.jwt.get_unverified_header方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.get_unverified_header方法的具体用法?Python jwt.get_unverified_header怎么用?Python jwt.get_unverified_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jose.jwt的用法示例。


在下文中一共展示了jwt.get_unverified_header方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: verify_token

# 需要导入模块: from jose import jwt [as 别名]
# 或者: from jose.jwt import get_unverified_header [as 别名]
def verify_token(self,token,id_name,token_use):
        kid = jwt.get_unverified_header(token).get('kid')
        unverified_claims = jwt.get_unverified_claims(token)
        token_use_verified = unverified_claims.get('token_use') == token_use
        if not token_use_verified:
            raise TokenVerificationException('Your {} token use could not be verified.')
        hmac_key = self.get_key(kid)
        try:
            verified = jwt.decode(token,hmac_key,algorithms=['RS256'],
                   audience=unverified_claims.get('aud'),
                   issuer=unverified_claims.get('iss'))
        except JWTError:
            raise TokenVerificationException('Your {} token could not be verified.')
        setattr(self,id_name,token)
        return verified 
开发者ID:capless,项目名称:warrant,代码行数:17,代码来源:__init__.py

示例2: _get_jwt_public_key

# 需要导入模块: from jose import jwt [as 别名]
# 或者: from jose.jwt import get_unverified_header [as 别名]
def _get_jwt_public_key(self, id_token: str) -> Optional[Dict[str, str]]:
        """Method to get the public key for JWT signing

        Args:
            id_token(str): The JSON Web Token received from the identity provider

        Returns:
            dict
        """
        key_path = os.path.join(self.config.config['git']['working_directory'], '.labmanager', 'identity')
        if not os.path.exists(key_path):
            os.makedirs(key_path)

        key_file = os.path.join(key_path, "jwks.json")
        # Check for local cached key data
        if os.path.exists(key_file):
            with open(key_file, 'rt') as jwk_file:
                jwks = json.load(jwk_file)

        else:
            try:
                url = "https://" + self.config.config['auth']['provider_domain'] + "/.well-known/jwks.json"
                response = requests.get(url)
            except Exception as err:
                logger.info(type(err))
                logger.info(err)
                raise AuthenticationError(str(err), 401)

            if response.status_code != 200:
                raise AuthenticationError("Failed to load public RSA key to validate Bearer token", 401)

            jwks = response.json()

            # Save for later use
            if os.path.exists(key_path):
                with open(key_file, 'wt') as jwk_file:
                    json.dump(jwks, jwk_file)

            logger.info("Fetched RSA key from server and saved to disk")

        # Load header
        try:
            unverified_header = jwt.get_unverified_header(id_token)
        except jwt.JWTError as err:
            raise AuthenticationError(str(err), 401)

        rsa_key: dict = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"]
                }

        return rsa_key 
开发者ID:gigantum,项目名称:gigantum-client,代码行数:60,代码来源:identity.py

示例3: requires_auth

# 需要导入模块: from jose import jwt [as 别名]
# 或者: from jose.jwt import get_unverified_header [as 别名]
def requires_auth(f):
    """Determines if the Access Token is valid
    """

    @wraps(f)
    def decorated(*args, **kwargs):
        token = get_token_auth_header()
        jsonurl = urlopen("https://" + AUTH0_DOMAIN + "/.well-known/jwks.json")
        jwks = json.loads(jsonurl.read())
        unverified_header = jwt.get_unverified_header(token)
        rsa_key = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"],
                }
        if rsa_key:
            try:
                payload = jwt.decode(
                    token,
                    rsa_key,
                    algorithms=ALGORITHMS,
                    audience=API_AUDIENCE,
                    issuer="https://" + AUTH0_DOMAIN + "/",
                )
            except jwt.ExpiredSignatureError:
                abort(401, "Authorization token is expired")
            except jwt.JWTClaimsError:
                abort(
                    401,
                    "Authorization claim is incorrect, please check audience and issuer",
                )
            except Exception:
                abort(401, "Authorization header cannot be parsed")
            _request_ctx_stack.top.current_user = payload
            return f(*args, **kwargs)
        else:
            abort(401, "Authorization error, unable to find appropriate key")

    return decorated 
开发者ID:mozilla,项目名称:service-map,代码行数:46,代码来源:auth.py

示例4: requires_auth

# 需要导入模块: from jose import jwt [as 别名]
# 或者: from jose.jwt import get_unverified_header [as 别名]
def requires_auth(f):
    """Determines if the access token is valid
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        token = get_token_auth_header()
        jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
        jwks = json.loads(jsonurl.read())
        try:
            unverified_header = jwt.get_unverified_header(token)
        except jwt.JWTError:
            raise AuthError({"code": "invalid_header",
                            "description":
                                "Invalid header. "
                                "Use an RS256 signed JWT Access Token"}, 401)
        if unverified_header["alg"] == "HS256":
            raise AuthError({"code": "invalid_header",
                            "description":
                                "Invalid header. "
                                "Use an RS256 signed JWT Access Token"}, 401)
        rsa_key = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"]
                }
        if rsa_key:
            try:
                payload = jwt.decode(
                    token,
                    rsa_key,
                    algorithms=ALGORITHMS,
                    audience=API_IDENTIFIER,
                    issuer="https://"+AUTH0_DOMAIN+"/"
                )
            except jwt.ExpiredSignatureError:
                raise AuthError({"code": "token_expired",
                                "description": "token is expired"}, 401)
            except jwt.JWTClaimsError:
                raise AuthError({"code": "invalid_claims",
                                "description":
                                    "incorrect claims,"
                                    " please check the audience and issuer"}, 401)
            except Exception:
                raise AuthError({"code": "invalid_header",
                                "description":
                                    "Unable to parse authentication"
                                    " token."}, 401)

            _request_ctx_stack.top.current_user = payload
            return f(*args, **kwargs)
        raise AuthError({"code": "invalid_header",
                        "description": "Unable to find appropriate key"}, 401)
    return decorated


# Controllers API 
开发者ID:auth0-samples,项目名称:auth0-python-api-samples,代码行数:63,代码来源:server.py


注:本文中的jose.jwt.get_unverified_header方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。