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


Python jwt.PyJWTError方法代碼示例

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


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

示例1: get_current_user

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except PyJWTError:
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:20,代碼來源:tutorial004.py

示例2: __call__

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def __call__(
        self, credentials: Optional[str], user_db: BaseUserDatabase,
    ) -> Optional[BaseUserDB]:
        if credentials is None:
            return None

        try:
            data = jwt.decode(
                credentials,
                self.secret,
                audience=self.token_audience,
                algorithms=[JWT_ALGORITHM],
            )
            user_id = data.get("user_id")
            if user_id is None:
                return None
        except jwt.PyJWTError:
            return None

        try:
            user_uiid = UUID4(user_id)
            return await user_db.get(user_uiid)
        except ValueError:
            return None 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:26,代碼來源:jwt.py

示例3: tus_check_session

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def tus_check_session(request):
    try:
        secret = request.app['config']['manager']['secret']
        token = request.match_info['session']
        params = jwt.decode(token, secret, algorithms=['HS256'])
    except jwt.PyJWTError:
        log.exception('jwt error while parsing "{}"', token)
        raise InvalidAPIParameters('Could not validate the upload session token.')

    headers = await tus_session_headers(request, params)
    return web.Response(headers=headers) 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:13,代碼來源:vfolder.py

示例4: tus_upload_part

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def tus_upload_part(request):
    try:
        secret = request.app['config']['manager']['secret']
        token = request.match_info['session']
        params = jwt.decode(token, secret, algorithms=['HS256'])
    except jwt.PyJWTError:
        log.exception('jwt error while parsing "{}"', token)
        raise InvalidAPIParameters('Could not validate the upload session token.')

    headers = await tus_session_headers(request, params)

    folder_path = (request.app['VFOLDER_MOUNT'] / params['host'] /
                   request.app['VFOLDER_FSPREFIX'] / params['folder'])
    upload_base = folder_path / ".upload"
    target_filename = upload_base / params['session_id']

    async with AsyncFileWriter(
            loop=current_loop(),
            target_filename=target_filename,
            access_mode='ab',
            max_chunks=DEFAULT_INFLIGHT_CHUNKS) as writer:
        while not request.content.at_eof():
            chunk = await request.content.read(DEFAULT_CHUNK_SIZE)
            await writer.write(chunk)

    fs = Path(target_filename).stat().st_size
    if fs >= params['size']:
        target_path = folder_path / params['path']
        Path(target_filename).rename(target_path)
        try:
            loop = current_loop()
            await loop.run_in_executor(None, lambda: upload_base.rmdir())
        except OSError:
            pass

    headers['Upload-Offset'] = str(fs)
    return web.Response(status=204, headers=headers) 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:39,代碼來源:vfolder.py

示例5: get_current_user

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_current_user(token: str = Security(reusable_oauth2)):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
        )
    bucket = get_default_bucket()
    user = crud.user.get(bucket, username=token_data.username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:15,代碼來源:security.py

示例6: validate_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def validate_token(self, data):
        """Verify token is valid."""
        try:
            payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise serializers.ValidationError('Verification link has expired.')
        except jwt.PyJWTError:
            raise serializers.ValidationError('Invalid token')
        if payload['type'] != 'email_confirmation':
            raise serializers.ValidationError('Invalid token')

        self.context['payload'] = payload
        return data 
開發者ID:pablotrinidad,項目名稱:cride-platzi,代碼行數:15,代碼來源:users.py

示例7: get_current_user

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_current_user(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = f"Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (PyJWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:34,代碼來源:tutorial005.py

示例8: get_username_from_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_username_from_token(token: str, secret_key: str) -> str:
    try:
        return JWTUser(**jwt.decode(token, secret_key, algorithms=[ALGORITHM])).username
    except jwt.PyJWTError as decode_error:
        raise ValueError("unable to decode JWT token") from decode_error
    except ValidationError as validation_error:
        raise ValueError("malformed payload in token") from validation_error 
開發者ID:nsidnev,項目名稱:fastapi-realworld-example-app,代碼行數:9,代碼來源:jwt.py

示例9: get_current_user

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_current_user(
    db: Session = Depends(get_db), token: str = Security(reusable_oauth2)
):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
        )
    user = crud.user.get(db, id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=400, detail="User not found")
    return user 
開發者ID:QAX-A-Team,項目名稱:LuWu,代碼行數:16,代碼來源:security.py

示例10: get_current_user

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def get_current_user(self, token: str):
        """
        This decodes the jwt based on the secret and on the algorithm
        set on the LoginManager.
        If the token is correctly formatted and the user is found
        the user is returned else this raises a `fastapi.HTTPException`

        :param str token: The encoded jwt token
        :return: The user object returned by `self._user_callback`
        :raise: HTTPException if the token is invalid or the user is not found
        """
        try:
            payload = jwt.decode(
                token,
                str(self.secret),
                algorithms=[self.algorithm]
            )
            # the identifier should be stored under the sub (subject) key
            user_identifier = payload.get('sub')
            if user_identifier is None:
                raise InvalidCredentialsException
        except jwt.PyJWTError:
            raise InvalidCredentialsException

        user = await self._load_user(user_identifier)

        if user is None:
            raise InvalidCredentialsException

        return user 
開發者ID:MushroomMaula,項目名稱:fastapi_login,代碼行數:32,代碼來源:fastapi_login.py

示例11: download_with_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [as 別名]
def download_with_token(request) -> web.StreamResponse:
    try:
        secret = request.app['config']['manager']['secret']
        token = request.query.get('token', '')
        params = jwt.decode(token, secret, algorithms=['HS256'])
    except jwt.PyJWTError:
        log.exception('jwt error while parsing "{}"', token)
        raise InvalidAPIParameters('Could not validate the download token.')

    iv = t.Dict({
        t.Key('file'): t.String,
        t.Key('host'): t.String,
        t.Key('id'): t.String,
        t.Key('exp'): t.Int,
        t.Key('archive', default=False): t.Bool | t.Null,
    })
    params = iv.check(params)
    fn = params['file']
    log.info('VFOLDER.DOWNLOAD_WITH_TOKEN (token:{}, path:{})', token, fn)
    dbpool = request.app['dbpool']
    async with dbpool.acquire() as conn:
        query = (sa.select([vfolders.c.unmanaged_path])
                   .select_from(vfolders)
                   .where(vfolders.c.id == params['id'])
                   .limit(1))
        unmanaged_path = await conn.scalar(query)
        if unmanaged_path:
            folder_path = Path(unmanaged_path)
        else:
            folder_path = (request.app['VFOLDER_MOUNT'] / params['host'] /
                           request.app['VFOLDER_FSPREFIX'] / params['id'])
    try:
        file_path = (folder_path / fn).resolve()
        file_path.relative_to(folder_path)
        if not file_path.exists():
            raise FileNotFoundError
    except (ValueError, FileNotFoundError):
        raise InvalidAPIParameters('The file is not found.')
    if not file_path.is_file():
        if params['archive']:
            # Download directory as an archive when archive param is set.
            return await download_directory_as_archive(request, file_path)
        else:
            raise InvalidAPIParameters('The file is not a regular file.')
    if request.method == 'HEAD':
        return web.Response(status=200, headers={
            hdrs.ACCEPT_RANGES: 'bytes',
            hdrs.CONTENT_LENGTH: str(file_path.stat().st_size),
        })
    ascii_filename = file_path.name.encode('ascii', errors='ignore').decode('ascii').replace('"', r'\"')
    encoded_filename = urllib.parse.quote(file_path.name, encoding='utf-8')
    return web.FileResponse(file_path, headers={
        hdrs.CONTENT_TYPE: "application/octet-stream",
        hdrs.CONTENT_DISPOSITION: " ".join([
            "attachment;"
            f"filename=\"{ascii_filename}\";",       # RFC-2616 sec2.2
            f"filename*=UTF-8''{encoded_filename}",  # RFC-5987
        ])
    }) 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:61,代碼來源:vfolder.py

示例12: get_claims

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import PyJWTError [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 
開發者ID:AngellusMortis,項目名稱:django_microsoft_auth,代碼行數:44,代碼來源:client.py


注:本文中的jwt.PyJWTError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。