Python jwt.PyJWTError() Examples
The following are 13
code examples of jwt.PyJWTError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jwt
, or try the search function
.
Example #1
Source File: tutorial004.py From fastapi with MIT License | 6 votes |
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
Example #2
Source File: jwt.py From fastapi-users with MIT License | 6 votes |
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
Example #3
Source File: cookie.py From fastapi-users with MIT License | 6 votes |
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
Example #4
Source File: vfolder.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 5 votes |
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)
Example #5
Source File: vfolder.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 5 votes |
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)
Example #6
Source File: security.py From full-stack-fastapi-couchbase with MIT License | 5 votes |
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
Example #7
Source File: users.py From cride-platzi with MIT License | 5 votes |
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
Example #8
Source File: tutorial005.py From fastapi with MIT License | 5 votes |
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
Example #9
Source File: jwt.py From fastapi-realworld-example-app with MIT License | 5 votes |
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
Example #10
Source File: security.py From LuWu with Apache License 2.0 | 5 votes |
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
Example #11
Source File: fastapi_login.py From fastapi_login with MIT License | 5 votes |
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
Example #12
Source File: vfolder.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 4 votes |
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 ]) })
Example #13
Source File: client.py From django_microsoft_auth with MIT License | 4 votes |
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