def __init__(self, config_file=None): if config_file is None: self.__config = Config.from_default_files() else: self.__config = Config.from_files([config_file]) # configure logging if self.__config.log_file is None or \ self.__config.log_file == "/dev/stderr": log_handler = logging.StreamHandler() elif self.__config.log_file == "/dev/stdout": log_handler = logging.StreamHandler(sys.stdout) else: try: log_handler = logging.handlers.RotatingFileHandler( self.__config.log_file, maxBytes=100**6, backupCount=2) except Exception: # anything goes wrong, fallback to stderr log_handler = logging.StreamHandler() log_format = "[%(asctime)s] [%(name)s] %(levelname)s - %(message)s" logging.basicConfig(level=self.__config.log_level, handlers=[log_handler], format=log_format, datefmt='%Y-%m-%d %H:%M:%S') self.__user_security = HTTPBearer() self.__admin_security = HTTPBearer() self.__authorisation = Authorisation(self.__config) self.__lum = LocalUserManager()
class AuthHandler: security = HTTPBearer() password_context = CryptContext(schemes=['bcrypt'], deprecated="auto") secret = 'SECRET' def get_password_hash(self, password): return self.password_context.hash(password) def verify_password(self, plain_password, hashed_password): return self.password_context.verify(plain_password, hashed_password) def encode_token(self, user_id): payload = { # TODO verificar tempo de expiração 'sub': user_id } return jwt.encode(payload, self.secret, algorithm='HS256') def decode_token(self, token): try: payload = jwt.decode(token, self.secret, algorithms=['HS256']) return payload['sub'] except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail='Signature Expired') except jwt.InvalidTokenError as e: raise HTTPException(status_code=401, detail='Invalid token') def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
def check_token(auth_token=Depends(HTTPBearer( scheme_name="bearerAuth", bearerFormat="JWT", auto_error=False, ))): """ Check valid token :param auth_token: :return: str """ if auth_token is None: raise UnauthorisedException() try: payload = jwt.decode( auth_token.credentials, Config.SECRET_KEY, algorithms=[Config.ALGORITHM] ) username: str = payload.get("sub") if username is None: raise JWTError except JWTError: raise UnauthorisedException("Access token is invalid") return username
class AuthHandler(): security = HTTPBearer() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") secret = 'SUPER DUPER SECRET' def get_password_hash(self, password): return self.pwd_context.hash(password) def verify_password(self, plain_password, hashed_password): return self.pwd_context.verify(plain_password, hashed_password) def encode_token(self, user_id): payload = { 'exp': datetime.utcnow() + timedelta(days=0, minutes=5), 'iat': datetime.utcnow(), 'sub': user_id } return jwt.encode(payload, self.secret, algorithm='HS256') def decode_token(self, token): try: payload = jwt.decode(token, self.secret, algorithms=['HS256']) return payload['sub'] except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail='Signature has expired') except jwt.InvalidTokenError as e: raise HTTPException(status_code=401, detail='Invalid token') def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
async def __call__( self, http_auth: HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> Optional[Type[BaseModel]]: """Get current user and verification with ID-token Shortcut. Use as (`Auth` is this subclass, `auth` is `Auth` instanse and `app` is fastapi.FastAPI instanse): ``` from fastapi import Depends @app.get("/") def api(current_user: Auth = Depends(auth)): return current_user ``` """ is_verified = self.verify_token(http_auth) if not is_verified: return None claims = jwt.get_unverified_claims(http_auth.credentials) try: current_user = self.user_info.parse_obj(claims) return current_user except ValidationError: if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Validation Error for Claims", ) else: return None
def sample( req: Request, full_path: str, token: str = fastapi.Depends(HTTPBearer( auto_error=False, scheme_name="Bearer" )) ): user = {} if token: user = jwt.decode(token, key=SECRET, algorithms="HS256") opa_input = { "input": { "method": req.method, "path": full_path.split("/"), "subject": { "username": user.get("username", None) } } } res = requests.post( "http://policies:8181/v1/data/authz/allow", json=opa_input, headers={"content-type": "application/json"} ) content = res.json() if ( not (r := content.get("result")) or r is False or res.status_code != status.HTTP_200_OK ): return Response(status_code=status.HTTP_403_FORBIDDEN)
async def get_user_list( limit: int = 10, prev: int = None, authorization: HTTPAuthorizationCredentials = Security(HTTPBearer()), ): extract_payload_from_token(token=authorization.credentials) return await GetUserListUsecase().execute(limit=limit, prev=prev)
async def __call__( self, http_auth: Optional[HTTPAuthorizationCredentials] = Depends( HTTPBearer(auto_error=False)), ) -> Any: """User access/ID-token verification Shortcut to pass it into dependencies. Use as (`auth` is this instanse and `app` is fastapi.FastAPI instanse): ``` from fastapi import Depends @app.get("/", dependencies=[Depends(auth)]) def api(): return "hello" ``` """ if http_auth is None: if self.verifier.auto_error: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=NOT_AUTHENTICATED) else: return None is_verified = self.verifier.verify_token(http_auth) if not is_verified: return None return await self.call(http_auth)
class AuthHandler(): security = HTTPBearer() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") def get_password_hash(self, password): return self.pwd_context.hash(password) def verify_password(self, plain_password, hashed_password): return self.pwd_context.verify(plain_password, hashed_password) # create jwt access token def create_access_token(self, email): payload = { 'exp': datetime.utcnow() + timedelta(int(config["ACCESS_TOKEN_EXPIRE_MINUTES"])), 'sub': email } return jwt.encode( payload, config["SECRET_KEY"], algorithm=config["ALGORITHM"] ) def decode_token(self, token): try: payload = jwt.decode(token, config["SECRET_KEY"], algorithms=[config["ALGORITHM"]]) return payload["sub"] except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail='Signature has expired') except jwt.InvalidTokenError: raise HTTPException(status_code=401, detail='Invalid Token') def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
async def __call__( self, request: Request, token: HTTPAuthorizationCredentials = Depends(HTTPBearer()), ) -> dict: jwt_header = jwt.get_unverified_header(token.credentials) await self._fetch_public_keys() for public_key in self._public_keys or []: if public_key["kid"] == jwt_header["kid"]: try: claims = jwt.decode( token.credentials, public_key, audience=self.audience or str(request.url), issuer=self.issuer, ) except Exception as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid Token {e}", ) return claims else: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unknown Token")
class AuthHandler(): security = HTTPBearer() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") secret = 'SECRET' def get_password_hash(self, password): return self.pwd_context.hash(password) def verify_password(self, plain_password, hashed_password): return self.pwd_context.verify(plain_password, hashed_password) def encode_token(self, user_id): db = connectDB() token = uuid.uuid4().hex db['tokens'].insert_one({"token": token, "userId": user_id}) return token def decode_token(self, token): db = connectDB() theToken = db['tokens'].find_one({"token": token}) return theToken['userId'] def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
def authenticate( token: Optional[HTTPAuthorizationCredentials] = Depends( HTTPBearer(auto_error=False)), x_goog_iap_jwt_assertion: Optional[str] = Depends(get_jwt_from_request), ) -> str: """ If a token (OR Google IAP auth jwt) is provided, return the email, else raise an Exception """ if x_goog_iap_jwt_assertion: # We have to PREFER the IAP's identity, otherwise you could have a case where # the JWT is forged, but IAP lets it through and authenticates, but then we take # the identity then without checking. return validate_iap_jwt_and_get_email(x_goog_iap_jwt_assertion, audience=EXPECTED_AUDIENCE) if token: return email_from_id_token(token.credentials) if DEFAULT_USER is not None: # this should only happen in LOCAL environments logging.info(f'Using {DEFAULT_USER} as authenticated user') return DEFAULT_USER raise HTTPException(status_code=401, detail=f'Not authenticated :(')
async def create_user( request: CreateUserRequestSchema, authorization: HTTPAuthorizationCredentials = Security(HTTPBearer()), ): extract_payload_from_token(token=authorization.credentials) with Transaction(): user = await CreateUserUsecase().execute(**request.dict()) return user
async def valid_token( auth: HTTPAuthorizationCredentials = Depends(HTTPBearer()), ) -> str: if auth.credentials == DUMMY_CREDENTIALS: return 'dummy' raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, )
async def bearer_auth( request: Request, http_credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer()), # pylint: disable=unused-argument ) -> Optional[str]: """Auth dependence, scope data set in TokenAuthMiddleware.""" token_data: Dict[str, str] = request.scope.get("token_data", {}) user_id: Optional[str] = token_data.get("user_id") return user_id
async def __call__( self, authorization_code: HTTPAuthorizationCredentials = Depends(HTTPBearer(auto_error=False)), ) -> UserInfo: if authorization_code is None and self.auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" ) return await oauth.server.parse_id_token_raw(authorization_code.credentials)
class AuthHandler(): security = HTTPBearer() pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto') secret = SECRET_KEY @classmethod async def get_password_hash(cls, password: str): return cls.pwd_context.hash(password) @classmethod async def verify_password(cls, plain_password: str, hashed_password: str): return cls.pwd_context.verify(plain_password, hashed_password) @classmethod async def encode_token(cls, username: str, privileges: str): is_admin: bool = False if privileges == 'Admin' or privileges == 'Super Admin': is_admin = True payload = { 'exp': datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES), 'iat': datetime.utcnow(), 'sub': { 'identity': { 'id': username, 'privileges': privileges, }, 'claims': { 'is_admin': is_admin } } } return jwt.encode(payload, cls.secret, algorithm=ALGORITHM) @classmethod def decode_token(cls, token: str): try: payload = jwt.decode(token, cls.secret, algorithms=[ALGORITHM]) return payload['sub'] except jwt.ExpiredSignatureError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORISED, detail='Signature has expired') except jwt.InvalidTokenError as e: print( f'============================== \\n Auth Error: {e} \\n ==============================' ) raise HTTPException(status_code=status.HTTP_401_UNAUTHORISED, detail='Invalid token') @classmethod def auth_wrapper(cls, auth: HTTPAuthorizationCredentials = Security(security)): return cls.decode_token(auth.credentials)
async def __call__( self, http_auth: HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> Optional[bool]: is_verified = self.verify_token(http_auth) if not is_verified: return None if self.scope_name: is_verified_scope = self.verify_scope(http_auth) if not is_verified_scope: return None return True
async def verify_token( token : HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> Any: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: jwt.decode(getattr(token,'credentials'), settings.SECRET_KEY, algorithms=[security.ALGORITHM]) except (PyJWTError, ValidationError): raise credentials_exception return True
class AuthHandler(): """ Initialize instances """ security = HTTPBearer() # This will allow of hashing of the user's password password_context = CryptContext(schemes=['bcrypt'], deprecated='auto') secret = 'SECRET' """ GET HASHED PASSWORD """ def get_hashed_password(self, password): return self.password_context.hash(password) """GET AND VERIFIY THE PASSWORD IF PLAIN PASS IS A MATCH WITH THE HASHED PASS""" def get_verify_password(self, plaintext_password, hashed_password): return self.password_context.verify(plaintext_password, hashed_password) """ ENCODE TOKEN """ def enconde_token(self, user_id, user_fullname, username, user_email): # def enconde_token(self, username, user_email): payload = { 'exp': datetime.utcnow() + timedelta(days=0, minutes=0.5), 'iat': datetime.utcnow(), 'user_id': user_id, 'username': username, 'user_fullname': user_fullname, 'email': user_email } return jwt.encode(payload, self.secret, algorithm='HS256') """ DECODE TOKEN """ def decode_token(self, token): try: payload = jwt.decode(token, self.secret, algorithms=['HS256']) # print(payload) # return payload['sub'] return payload except jwt.ExpiredSignatureError: """ IF TOKEN PASSED 5 MIN, IT WILL RAISE AN EXCEPTION """ raise HTTPException(status_code=401, detail='Signature has expired') except jwt.InvalidTokenError as e: """ IF PASSWORD DOESNT MATCH THE HASHED PASSWORD, IT WILL RAISE AN EXCEPTION """ raise HTTPException(status_code=401, detail='Invalid token') def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
async def me(credentials: HTTPAuthorizationCredentials = Security( HTTPBearer())): """ Presents info encoded in the JWT token. The token itself is verified by the JWTBearer class through dependency injection. Execution of this route's functions means the token has already been validated. """ decoded_token = decode_token(credentials.credentials) exp = datetime.utcfromtimestamp( decoded_token.get("exp")).strftime('%Y-%m-%dT%H:%M:%SZ') return f"""
def bearer_authentication(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())) -> str: try: payload = jwt.decode(credentials.credentials, 'secret_key-Y01oEAl3iz', algorithms=["HS512", "HS256"]) username: str = payload.get("sub") if username is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Non username") if username not in ["jes"]: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions") return username except jwt.DecodeError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") except jwt.ExpiredSignatureError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="expired token")
def verify_token_and_domain( request: Request, Authorize: AuthJWT = Depends(), dummy=Depends(HTTPBearer()) ) -> RawJwt: """ Check JWT access token and domain, if domain from request anf from token are equal, than pass the validation. Argument dummy needs only for generating the documentation. """ domain = request.base_url.hostname Authorize.jwt_required() raw_jwt = Authorize.get_raw_jwt() user_domain = raw_jwt.get('domain') if domain != user_domain: raise HTTPException(401) return raw_jwt
class AuthHandler(): security = HTTPBearer() password_context = CryptContext(schemes=["bcrypt"], deprecated="auto") secret = os.environ['SECRET'] #refresh_secret = os.environ['REFRESH_SECRET'] def hash_password(self, password: str): return self.password_context.hash(password) def verify_password(self, plain_password: str, hashed_password: str): return self.password_context.verify(plain_password, hashed_password) def encode_token(self, subject: Union[str, Any], expires_delta: timedelta = None): if expires_delta: time_expiration = datetime.utcnow() + expires_delta else: time_expiration = datetime.utcnow() + timedelta(days=0, minutes=30) if isinstance(subject, UUID): subject = str(subject) payload = { 'iat': datetime.utcnow(), 'exp': time_expiration, 'sub': subject } secret = self.secret return jwt.encode(payload, secret, algorithm='HS256') def decode_token(self, token: str): try: payload = jwt.decode(token, self.secret, algorithms=['HS256']) return payload['sub'] except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail='Assinatura do token expirada.') except jwt.InvalidTokenError as e: raise HTTPException(status_code=401, detail='Token inválido.') def wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
class AuthHandler: security = HTTPBearer() # decoding access token and getting the user email for that token def decode_token(self, token, db: Session = Depends(get_db)): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) email: str = payload.get("sub") if email is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Credentials", ) token_data_ex = token_data.TokenData(email=email) except JWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Credentials") user = user_crud.get_user_by_email(db, email=token_data_ex.email) if user is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Credentials") return user # function for token authorization def auth_wrapper( self, auth: HTTPAuthorizationCredentials = Security(security), db: Session = Depends(get_db), ): return self.decode_token(auth.credentials, db)
async def get_current_user( db: Session = Depends(get_db), token : HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> models.Users: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(getattr(token,'credentials'), settings.SECRET_KEY, algorithms=[security.ALGORITHM]) token_data = schemas.TokenData(**payload) except (PyJWTError, ValidationError): raise credentials_exception user = crud.user.get(db,id=token_data.sub) if user is None: raise credentials_exception return user
class AuthHandler: security = HTTPBearer() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") # openssl rand -hex 32 SECRET_KEY = os.environ.get("JWT_SECRET_KEY_PROD") if SECRET_KEY in (None, "None", "NA", "N.A.", ""): SECRET_KEY = "replace_me_replace_me_replace_me" ALGORITHM = "HS256" # HS256 (HMAC with SHA-256) ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours def get_password_hash(self, password: str) -> str: return self.pwd_context.hash(password) def verify_password(self, plain_password: str, hashed_password: str) -> bool: return self.pwd_context.verify(plain_password, hashed_password) def encode_token(self, user_id: str) -> str: payload = { "exp": datetime.utcnow() + timedelta(days=0, minutes=self.ACCESS_TOKEN_EXPIRE_MINUTES), "iat": datetime.utcnow(), "sub": user_id, } return jwt.encode(payload, self.SECRET_KEY, algorithm=self.ALGORITHM) def decode_token(self, token: str) -> str: try: payload = jwt.decode(token, self.SECRET_KEY, algorithms=[self.ALGORITHM]) return payload["sub"] except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail="Signature has expired") except jwt.InvalidTokenError as e: raise HTTPException(status_code=401, detail="Invalid token") def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): return self.decode_token(auth.credentials)
def get_current_user(cred: HTTPAuthorizationCredentials = Depends( HTTPBearer())): """ トークン認証しユーザー情報を返す """ try: # token認証 with session_scope() as s: u = s.query(Token).filter(Token.token == cred.credentials).first() # userがいる場合 if u: return u.user_id else: raise Exception except Exception: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid authentication credentials', headers={'WWW-Authenticate': 'Bearer'}, )
async def __call__( self, http_auth: HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> Optional[Type[BaseModel]]: is_verified = self.verify_token(http_auth) if not is_verified: return None claims = jwt.get_unverified_claims(http_auth.credentials) try: current_user = self.user_info.parse_obj(claims) return current_user except ValidationError: if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Validation Error for Claims", ) else: return None
class AuthHandler: security = HTTPBearer() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") secret = "SECRET" def get_password_hash(self, password): return self.pwd_context.hash(password) def verify_password(self, plain_password, hashed_password): return self.pwd_context.verify(plain_password, hashed_password) def encode_token(self, user_id): payload = { "exp": datetime.utcnow() + timedelta(days=0, seconds=10), "iat": datetime.utcnow(), "sub": user_id, } print(payload) test = jwt.encode(payload, self.secret, algorithm="HS256") print(test) return jwt.encode(payload, self.secret, algorithm="HS256") def decode_token(self, token): try: payload = jwt.decode(token, self.secret, algorithms=["HS256"]) print(payload) print(payload["sub"]) except jwt.ExpiredSignatureError: print("Expired") raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Signature has expired") except jwt.InvalidTokenError as e: print(e) raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)): print(self.decode_token(auth.credentials)) return self.decode_token(auth.credentials)