本文整理汇总了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
示例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
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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
])
})
示例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