當前位置: 首頁>>代碼示例>>Python>>正文


Python jwt.JWTError方法代碼示例

本文整理匯總了Python中jose.jwt.JWTError方法的典型用法代碼示例。如果您正苦於以下問題:Python jwt.JWTError方法的具體用法?Python jwt.JWTError怎麽用?Python jwt.JWTError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jose.jwt的用法示例。


在下文中一共展示了jwt.JWTError方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: middleware

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [as 別名]
def middleware(self, request, handler):
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer'):
            token = token[7:]
        else:
            token = request.rel_url.query.get('token')
            if not token:
                token = request.headers.get('token')
        request.verified = False

        if token:
            try:
                payload = self.decode(token)
                request.verified = True
            except jwt.JWTError:
                raise web.HTTPUnauthorized()
        else:
            payload = {}
        request.session = payload
        return await handler(request) 
開發者ID:dvhb,項目名稱:dvhb-hybrid,代碼行數:22,代碼來源:jwt.py

示例2: get_current_user

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [as 別名]
def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = crud.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-postgresql,代碼行數:19,代碼來源:deps.py

示例3: validate_and_return_id_token

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [as 別名]
def validate_and_return_id_token(self, id_token, access_token):
        """
        Validates the id_token according to the steps at
        http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation.
        """
        key = self.find_valid_key(id_token)

        if not key:
            raise AuthTokenError(self, "Signature verification failed")

        alg = key["alg"]
        rsa_key = jwk.construct(key)

        k = {
            "alg": rsa_key._algorithm,  # pylint: disable=protected-access
            "kty": "oct",
            "k": base64.urlsafe_b64encode(rsa_key.prepared_key)
            .rstrip(b"=")
            .decode("utf-8"),
        }

        try:
            claims = jwt.decode(
                id_token,
                k,
                algorithms=[alg],
                audience=self.setting("KEY"),
                issuer=self.id_token_issuer(),
                options=self.JWT_DECODE_OPTIONS,
            )
        except ExpiredSignatureError:
            raise AuthTokenError(self, "Signature has expired")
        except JWTClaimsError as error:
            raise AuthTokenError(self, str(error))
        except JWTError:
            raise AuthTokenError(self, "Invalid signature")

        self.validate_claims(claims) 
開發者ID:openfun,項目名稱:richie,代碼行數:40,代碼來源:backends.py

示例4: verify_password_reset_token

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [as 別名]
def verify_password_reset_token(token: str) -> Optional[str]:
    try:
        decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
        return decoded_token["email"]
    except jwt.JWTError:
        return None 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-postgresql,代碼行數:8,代碼來源:utils.py

示例5: _get_jwt_public_key

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [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

示例6: requires_auth

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import JWTError [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.JWTError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。