async def __call__( self, request: Request) -> Optional[HTTPAuthorizationCredentials]: authorization_in_request: str = request.headers.get("Authorization") authorization_in_cookie: str = request.cookies.get("Authorization") if authorization_in_request: scheme, credentials = get_authorization_scheme_param( authorization_in_request) elif authorization_in_cookie: scheme, credentials = get_authorization_scheme_param( authorization_in_cookie) else: scheme, credentials = None, None if not (scheme and credentials): if self.auto_error: raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated") else: return None if scheme.lower() != "bearer": if self.auto_error: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", ) else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
async def __call__(self, request: Request) -> Optional[str]: header_authorization: str = request.headers.get("Authorization") cookie_authorization: str = request.cookies.get("Authorization") header_scheme, header_param = get_authorization_scheme_param( header_authorization) cookie_scheme, cookie_param = get_authorization_scheme_param( cookie_authorization) if header_scheme.lower() == "bearer": authorization = True scheme = header_scheme param = header_param elif cookie_scheme.lower() == "bearer": authorization = True scheme = cookie_scheme param = cookie_param else: authorization = False if not authorization or scheme.lower() != "bearer": if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None return param
def __call__(self, request: Request) -> Optional[str]: # type: ignore header_authorization: str = request.headers.get("Authorization") cookie_authorization: str = request.cookies.get( "Authorization") # type: ignore header_scheme, header_param = get_authorization_scheme_param( header_authorization) cookie_scheme, cookie_param = get_authorization_scheme_param( cookie_authorization) if header_scheme.lower() == "bearer": authorization = True scheme = header_scheme param = header_param elif cookie_scheme.lower() == "bearer": authorization = True scheme = cookie_scheme param = cookie_param else: authorization = False if not authorization or scheme.lower() != "bearer": raise RequiresLoginException("No Login Details") return param
async def __call__(self, request: Request) -> Optional[str]: header_authorization: str = request.headers.get("Authorization") cookie_authorization: str = request.cookies.get("Authorization") header_scheme, header_param = get_authorization_scheme_param(header_authorization) cookie_scheme, cookie_param = get_authorization_scheme_param(cookie_authorization) if header_scheme.lower() == "bearer": authorization = True scheme = header_scheme param = header_param elif cookie_scheme.lower() == "bearer": authorization = True scheme = cookie_scheme param = cookie_param else: authorization = False scheme = param = "" if not authorization or scheme.lower() != "bearer": if self.auto_error: raise UnauthorizedException() else: return None return param
async def __call__(self, request: Request) -> Optional[Dict[str, Any]]: # Fetch authorization header authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) # Verify authorization header if not (authorization and scheme and credentials): if self.auto_error: # pylint: disable=no-else-raise raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated") else: return None if scheme.lower() != "bearer": if self.auto_error: # pylint: disable=no-else-raise raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", ) else: return None # Validate the token try: payload = validate_locally( credentials, self.issuer, self.audience, self.client_ids, ) except Exception as e: raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid authentication token") from e return payload
async def get_current_user(request: Request) -> Optional[graphene_models.User]: authorization: str = request.headers.get("Authorization") if not authorization: return None _, token = utils.get_authorization_scheme_param(authorization) return await crud.get_current_user(token=token)
async def __call__(self, request: Request) -> Optional[str]: cookies: Optional[str] = request.cookies.get("Authorization") if not cookies: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") scheme, param = get_authorization_scheme_param(cookies) if scheme.lower() != "bearer": if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None else: try: s = verify_jwt(param) print("success", s) if 'name' in s: return s['name'] else: raise HTTPException( status_code=HTTP_500_INTERNAL_SERVER_ERROR, detail="Unable to obtain user") except Exception as e: print("exception", e) raise e
async def admin_basic_auth(authorization: Optional[str] = Header( None)) -> bool: if not authorization: raise HTTPException(status_code=400, detail='No authorization header provided') scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != 'basic': raise HTTPException(status_code=400, detail='No basic authorization provided') decoded = base64.b64decode(param).decode("ascii") username, _, password = decoded.partition(":") if len(username.split(' ')) != 2: raise HTTPException( status_code=401, detail='No first name and last name for user name provided') cli = await get_database() admin = await get_admin_user( username.split(' ')[0], username.split(' ')[1], password, cli) if not admin: raise HTTPException(status_code=401, detail='No valid user found') return True
async def authenticate( self, conn: HTTPConnection) -> Tuple[bool, Optional[User]]: """ Main function that AuthenticationMiddleware uses from this backend. Should return whether request is authenticated based on credentials and if it was, return also user instance. :param conn: HTTPConnection of the current request-response cycle :return: 2-tuple: is authenticated & user instance if exists """ authorization: str = conn.headers.get("Authorization") if not authorization: return False, None scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): raise AuthenticationError("Not authenticated") if scheme.lower() != "token": raise AuthenticationError("Invalid authentication credentials") token = await Token.get( key=credentials, is_active=True, expires={"$not": { "$lt": get_now() }}, ) if token is None: return False, None conn.scope["token"] = token user = await User.get(id=token.user_id) if user is None: return False, None return True, user
async def __call__(self, websocket: WebSocket) -> WebSocket: # type: ignore authorization: str = websocket.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if self.realm: unauthorized_headers = { "WWW-Authenticate": f'Basic realm="{self.realm}"' } else: unauthorized_headers = {"WWW-Authenticate": "Basic"} invalid_user_credentials_exc = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers=unauthorized_headers, ) if not authorization or scheme.lower() != "basic": if self.auto_error: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers=unauthorized_headers, ) else: return None try: data = base64.b64decode(param).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error): raise invalid_user_credentials_exc username, separator, password = data.partition(":") if not separator: raise invalid_user_credentials_exc websocket.scope["user"] = UserModel(username=username, password=password) return websocket
async def authenticate(self, request: Request) -> None: """ 認証処理 Args: request (Request): リクエスト情報 """ authorization: str = request.headers.get('Authorization') scheme, access_token = get_authorization_scheme_param(authorization) # リクエストヘッダに認証情報が無い場合は「未承認ユーザー」を返す if not authorization or scheme.lower() != 'bearer': return authentication.AuthCredentials(['unauthenticated']), UnauthenticatedUser() # JWTをデコードしてクレームセットを取得 try: claims = jwt_decord_handler(access_token) # アクセストークン期限切れ except jwt.ExpiredSignatureError: raise ApiException(create_error(ErrorMessage.EXPIRED_TOKEN), status_code=status.HTTP_401_UNAUTHORIZED) # その他エラーの場合は「未承認ユーザー」を返す except Exception as e: print(e) return authentication.AuthCredentials(['unauthenticated']), UnauthenticatedUser() # クレームセットのユーザーIDでユーザーを取得 user = CRUDUser(request.state.db_session).get_by_id(claims['user_id']) # 下記いずれかの場合はエラー # ・ユーザーを取得できなかった場合 # ・ユーザーを取得できたが、非アクティブ if not user or not user.is_active: raise ApiException(create_error(ErrorMessage.INVALID_TOKEN)) return authentication.AuthCredentials(['authenticated']), AuthenticatedUser(user)
async def __call__(self, request: Request) -> Optional[str]: # type: ignore authorization: Optional[str] = request.headers.get("Authorization") scheme: Optional[str] = None credentials: Optional[str] = None if authorization: # This block handles either specifying the 'bearer' or not if len(authorization.split(' ')) > 1: scheme, credentials = get_authorization_scheme_param(authorization) else: scheme = 'bearer' credentials = authorization if not (authorization and scheme and credentials): if self.auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" ) return None if scheme.lower() != "bearer": if self.auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) return None return credentials
def get_user_from_header( *, request: Request, authorization: str = Header(None)) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: wrangler = socket.gethostbyname("emd-wrangler") if request.client.host == wrangler: return User(username="******", email="*****@*****.**", full_name="admin", roles=["admin"]) except Exception as e: print("cannot find host: emd-wrangler") scheme, token = get_authorization_scheme_param(authorization) if scheme.lower() != "bearer": raise credentials_exception try: tokenuser = is_token_valid(token) return tokenuser except Exception as e: raise credentials_exception
async def __call__( self, request: Request ) -> Tuple[bool, Union[dict, HTTPException]]: authorization: str = request.headers.get("Authorization") scheme, token = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": token = request.cookies.get(config.JWT_ACCESS_TOKEN_COOKIE) if not token: error = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) if self.auto_error: raise error else: return False, error try: token = jwt.decode(token, config.JWT_PUBLIC_KEY) token.validate() except ExpiredTokenError as e: error = HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail=str(e)) if self.auto_error: raise error else: return False, error except JoseError as e: error = HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e)) if self.auto_error: raise error else: return False, error return True, token
async def check_jwt_auth(request: Request) -> str: authorization: str = request.headers.get("Authorization") scheme, token = get_authorization_scheme_param(authorization) if scheme.lower() != "token": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid auth scheme {scheme}", headers={"WWW-Authenticate": "Token"}, ) try: payload = jwt.decode( token, key=conf.settings.jwt_secret, algorithms=[JWT_ALGORITHM] ) username: str = payload.get("sub") password = conf.settings.auth.get(username) if not (password and generate_pha(password) == payload.get("pha")): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid user {username}", headers={"WWW-Authenticate": "Token"}, ) return username except PyJWTError as je: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Token decode error: {je}", headers={"WWW-Authenticate": "Token"}, )
def load_from_request(self, request: Request): # Load user from any of the stores user = self._load_from_key( request) or self._delegate_stores_until_not_none( "load_from_request", request) if user: return user # Load JWT user from header if "headers" in manager.settings.jwt_token_location: scheme, token = get_authorization_scheme_param( request.headers.get(manager.settings.jwt_header_name)) if token and scheme.lower() == manager.settings.jwt_header_type: user = access_token_to_user(token) if user: return user # Load JWT user from cookie if "cookies" in manager.settings.jwt_token_location: token_from_cookie = request.cookies.get( manager.settings.jwt_access_cookie_name) if token_from_cookie: user = access_token_to_user(token_from_cookie) if user: return user # Raise an exception is no user could be loaded raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, )
async def __call__(self, request: Request) -> str: authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") return param
async def __call__(self, request: Request) -> Optional[str]: for url, op in settings.NO_VERIFY_URL.items(): if op == 'eq' and url == request.url.path.lower(): return None elif op == 'in' and url in request.url.path.lower(): return None authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None try: playload = jwt.decode(param, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) except jwt.ExpiredSignatureError: raise custom_exc.TokenExpired() except (jwt.JWTError, ValidationError, AttributeError): raise custom_exc.TokenAuthError() username = playload.get('username') user = await get_user_by_name(username=username) if not user: raise AuthenticationError("认证失败") """在 Request 对象中设置用户对象,这样在其他地方就能通过 request.state.user 获取到当前用户了""" request.state.user = user
async def get_token_if_present(request: Request): cookie_authorization: str = request.cookies.get("Authorization") cookie_scheme, cookie_param = get_authorization_scheme_param( cookie_authorization) token_data = (await get_token_contents(cookie_param) if cookie_authorization and cookie_param else None) return token_data
def get_current_user(*, request: Request): """Gets the current user based on the token.""" credentials_exception = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials") user_email = from_bearer_token(request) if not user_email: raise credentials_exception authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": raise credentials_exception token = authorization.split()[1] # TODO should we warm this cache up on application start? try: key = jwk_key_cache[JWKS_URL] except Exception: key = requests.get(JWKS_URL).json()["keys"][0] jwk_key_cache[JWKS_URL] = key try: data = jwt.decode(token, key) except JWTError: raise credentials_exception return data["email"]
async def __call__(self, ws: WebSocket) -> WebSocket: authorization: str = ws.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) else: return None if scheme.lower() != "bearer": if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) else: return None try: data = base64.b64decode(credentials).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) username, separator, password = data.partition(":") if not separator: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) ws.scope["user"] = UserModel(username=username, password=password) return ws
async def __call__( # type: ignore self, request: Request) -> Optional[HTTPBasicCredentials]: authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if self.realm: unauthorized_headers = { "WWW-Authenticate": f'Basic realm="{self.realm}"' } else: unauthorized_headers = {"WWW-Authenticate": "Basic"} invalid_user_credentials_exc = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers=unauthorized_headers, ) if not authorization or scheme.lower() != "basic": if self.auto_error: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers=unauthorized_headers, ) else: return None try: data = b64decode(param).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error): raise invalid_user_credentials_exc username, separator, password = data.partition(":") if not (separator): raise invalid_user_credentials_exc return HTTPBasicCredentials(username=username, password=password)
async def __call__(self, request: Request) -> str: authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
def get_token_from_cookie(request: Request) -> Optional[str]: value: Optional[str] = request.cookies.get(JWTMgr.COOKIE_KEY) if value is None: return None scheme, token = get_authorization_scheme_param(value) if scheme.lower() == "bearer": return token return None
async def __call__(self, request: Request): authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() not in ["bearer", "jwt"]: raise HTTPException(401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}) return param
async def __call__(self, request: Request) -> Optional[str]: authorization: str = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "basic": if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None return param
async def __call__(self, request: Request) -> Optional[str]: cookie_authorization: str = request.cookies.get("Authorization") cookie_scheme, cookie_param = get_authorization_scheme_param( cookie_authorization) if cookie_scheme.lower() != 'bearer': raise HTTPException(status_code=403, detail="Not authenticated") return cookie_param
async def root(Authorization: str = Header(None)) -> Dict: scheme, credentials = get_authorization_scheme_param(Authorization) if credentials: public_key = "b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs2iY+UNfz035EspzTZUeSai+FbBQC487BLsWC/BA+d5b1UFVs0k1erXnqrFBWjKzgn10r3fMfPlPn8ffK8iEuvBEoJ5vnRaHRqjhIi1DZ+h1o5sC9qhty0p5k+Nu9i0rV/CpY6PkAQw/e7kXBMWhK8zM/TAsA0GQUOaZDm/4WeNUq2roMAX+fAJZfMFiI2/WRvBQKcTY1SB6wJhC9c5QhBgWs83XR9EGP6BxyzvJMroR0kMyb+B7ITWbzpKXuUWbhsxRWm0Mz2nwHo9jsREC03wN0CnD+vocCnKjLv/4Bqy9igwKBT2bpAssR0Y7p3v1QZmSO3D4OxUhhkoWBZBCyQIDAQAB'" decoded = jwt.decode(credentials, key=public_key, verify=False) return {"message": "You're logged in!", "decoded_token": decoded} else: return {"message": "You're not logged in!"}
async def root(request: Request, ) -> Dict: authorization: str = request.cookies.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) decoded = jwt.decode( credentials, verify=False ) # TODO input keycloak public key as key, disable option to verify aud logger.debug(decoded) return {"message": "You're logged in!"}
async def authenticate(self, request): if self.headers.lower() not in request.headers: return AuthCredentials(), UnauthenticatedUser() auth = request.headers[self.headers] scheme, token = get_authorization_scheme_param(auth) if scheme.lower() != self.auth_type: return AuthCredentials(), UnauthenticatedUser() return self.verify_token(token)