async def is_authenticated(authorization=Security(APIKeyHeader(name="Authorization", auto_error=False))): if not authorization: raise CustomHTTPException( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel( type='error', message='Unauthorized' )] ) ) ) user_details = await UsersTableManager.is_valid_token(authorization) if not user_details: raise CustomHTTPException( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel( type='error', message='You are not authenticated' )] ) ) ) return format_user_details(user_details)
async def logout(authorization=Security(APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.post(f"{DB_SERVER_URL}/logout", headers={"Authorization": authorization}) return JSONResponse( status_code=response.status_code, content=response.json() ) except Exception as e: raise_exception(e)
async def get_users(query: str = Query(None), authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.get(f"{DB_SERVER_URL}/users", headers={"Authorization": authorization}, params={'query': query}) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def post_user(item: UserIn, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.post(f"{DB_SERVER_URL}/users", headers={"Authorization": authorization}, json=item.dict()) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def delete_user(id: int, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.delete(f"{DB_SERVER_URL}/users/{id}", headers={"Authorization": authorization}) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def put_group(id: int, item: BaseGroupIn, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.put(f"{DB_SERVER_URL}/groups/{id}", headers={"Authorization": authorization}, json=item.dict()) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
def authrization_heder_token( api_key: str = Depends(APIKeyHeader(name="Authorization")), ) -> str: try: token_prefix, token = api_key.split(" ") except ValueError: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="unsupported authorization type", ) if token_prefix != JWT_TOKEN_PREFIX: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="unsupported authorization type", ) return token
async def get_real_time_values(authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response_db = requests.get(f"{DB_SERVER_URL}/devices", headers={"Authorization": authorization}) response_rpi = requests.get(f"{RPI_SERVER_URL}/sensors", headers={"Authorization": authorization}) response_rpi_json = response_rpi.json() response_db_json = response_db.json() return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder( get_sensors_values(response_rpi_json['data'], response_db_json['data']))) except Exception as e: raise_exception(e)
async def get_reports(device_id: int = Query(None), report_date: datetime = Query(None), authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response = requests.get(f"{DB_SERVER_URL}/reports", headers={"Authorization": authorization}, params={ 'device_id': device_id, 'report_date': report_date }) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def have_permission(authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): user_id = (await is_authenticated(authorization))['id'] profile_id = await ProfilesTableManager.get_profile_id_by_profilename( 'admin') user_profiles = get_user_profile_id_list( await DelegationsTableManager.read_delegations(user_id=user_id)) if (not profile_id) or (profile_id not in user_profiles): raise CustomHTTPException( status_code=status.HTTP_403_FORBIDDEN, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel( type='error', message='You are not allowed to perform this action') ]))) return user_id
async def get_user(id: int, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response1 = requests.get(f"{DB_SERVER_URL}/users/{id}", headers={"Authorization": authorization}) user_details = response1.json() if len(user_details['data']) > 0: response2 = requests.get(f"{DB_SERVER_URL}/users/{id}/profiles", headers={"Authorization": authorization}) profiles = response2.json() user_details['data'][0]['profiles'] = get_user_profiles( profiles['data']) return JSONResponse(status_code=response1.status_code, content=user_details) except Exception as e: raise_exception(e)
async def create_alerts(item: AlertModel, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response_db = requests.get(f"{DB_SERVER_URL}/devices", headers={"Authorization": authorization}) alert = get_alert_value(item.dict(), (response_db.json())['data']) alert_json = {} if bool((alert.dict())['data']): alert_json = (alert.dict())['data'][0] response = requests.post(f"{DB_SERVER_URL}/alerts", headers={"Authorization": authorization}, json=alert_json) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def create_reports(items: List[ReportModel], authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response_db = requests.get(f"{DB_SERVER_URL}/devices", headers={"Authorization": authorization}) reports = get_report_values(items, (response_db.json())['data']) reports_list = [] if bool((reports.dict())['data']): reports_list = (reports.dict())['data'] response = requests.post(f"{DB_SERVER_URL}/reports", headers={"Authorization": authorization}, json=reports_list) return JSONResponse(status_code=response.status_code, content=response.json()) except Exception as e: raise_exception(e)
async def get_type(id: int, authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): try: response1 = requests.get(f"{DB_SERVER_URL}/types/{id}", headers={"Authorization": authorization}) type_details = response1.json() if len(type_details['data']) > 0: response2 = requests.get( f"{DB_SERVER_URL}/devices", headers={"Authorization": authorization}, params={'type_name': type_details['data'][0]['name']}) devices = response2.json() type_details['data'][0]['devices'] = get_type_devices( devices['data']) return JSONResponse(status_code=response1.status_code, content=type_details) except Exception as e: raise_exception(e)
import binascii import hmac import urllib.parse import json from fastapi import Depends, HTTPException, Request, Security from fastapi.security import APIKeyHeader from raddar.core.settings import settings GithubSignatureHeader = APIKeyHeader(name="X-Hub-Signature-256") async def valid_github_webhook( *, github_signature: str = Security(GithubSignatureHeader), request: Request): body = await request.body() signature = hmac.new( settings.api_key.get_secret_value().encode(), msg=body, digestmod="sha256", ) digest = f"sha256={signature.hexdigest()}" if not hmac.compare_digest(digest, github_signature): raise HTTPException(status_code=401, detail="Bad webhook secret")
from starlette.responses import RedirectResponse load_dotenv(find_dotenv()) openapi_prefix = os.getenv("CLUSTER_ROUTE_PREFIX", "").rstrip("/") app = FastAPI( title="spacy-ann-linker", version=__version__, description= "Remote Entity Linking with Approximate Nearest Neighbors index lookup for Aliases", openapi_prefix=openapi_prefix, ) example_request = srsly.read_json( Path(__file__).parent / "example_request.json") security = APIKeyHeader(name="api-key") @app.get("/", include_in_schema=False) def docs_redirect(): return RedirectResponse(f"{openapi_prefix}/docs") @app.post("/link", response_model=LinkingResponse) async def link( request: Request, # api_key = Depends(security), similarity_threshold: float = 0.65, body: LinkingRequest = Body(..., example=example_request), ): """Link batch of Spans to their canonical KnowledgeBase Id."""
from typing import Optional from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyHeader from pydantic import BaseModel from starlette.testclient import TestClient app = FastAPI() api_key = APIKeyHeader(name="key", auto_error=False) class User(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(api_key)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user( current_user: Optional[User] = Depends(get_current_user)): if current_user is None: return {"msg": "Create an account first"} return current_user
from fastapi import APIRouter, Depends, HTTPException from fastapi.security import APIKeyHeader from api import item api_router = APIRouter() API_KEY_SCHEME = APIKeyHeader(name='X-API-KEY') async def verify_api_key(api_key: str = Depends(API_KEY_SCHEME)): if api_key != "fake_api_key": raise HTTPException(status_code=400, detail="X-API-KEY header invalid") return api_key api_router.include_router( item.router, prefix="/items", tags=["items"], dependencies=[Depends(verify_api_key)], )
from fastapi import APIRouter, Depends, HTTPException, Security from sqlalchemy.orm import Session from starlette.responses import HTMLResponse from starlette.websockets import WebSocket from fastapi.security import APIKeyHeader from jinja2 import Environment, BaseLoader from .data import schema, crud from app.data.database import get_db from app.data.schema import SoftwarePackageStatus from .data.model import APIKey router = APIRouter() api_key_header = APIKeyHeader(name='access_token', auto_error=False) html = """ <!DOCTYPE html> <html> <body> <p id="message">Connecting...</p> <script> var ws = new WebSocket("ws://localhost:8000/packages/{{ id }}/{{ ws }}"); ws.onmessage = function(event) { document.getElementById("message").innerHTML = event.data; }; </script> </body> </html> """
from typing import Optional from fastapi import Security, HTTPException from fastapi.security import APIKeyQuery, APIKeyHeader, HTTPBearer, HTTPAuthorizationCredentials from starlette.status import HTTP_403_FORBIDDEN api_key_query = APIKeyQuery(name='apikey', auto_error=False) api_key_header = APIKeyHeader(name='X-API-Key', auto_error=False) bearer_header = HTTPBearer(auto_error=False) async def get_api_key( api_key_query_param: Optional[str] = Security(api_key_query), api_key_header_param: str = Security(api_key_header), bearer_header_param: Optional[HTTPAuthorizationCredentials] = Security( bearer_header), ): if api_key_query_param is not None: return api_key_query_param elif api_key_header_param is not None: return api_key_header_param elif bearer_header_param and bearer_header_param.scheme.lower( ) == "bearer": return bearer_header_param.credentials else: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="No credentials given")
from fastapi import Header, Security from authentication.models.users import User from fastapi.security import HTTPBasic, HTTPBasicCredentials, APIKeyHeader from typing import List from starlette.responses import Response from fastapi.encoders import jsonable_encoder from authentication.interfaces.database import database import jwt from starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED from datetime import datetime, timedelta from hashlib import sha256 from authentication.interfaces.token import verify_token router = APIRouter() security = HTTPBasic(auto_error=True) api_key = APIKeyHeader(name="x-api-key", auto_error=True) @router.post("/login", tags=["token"]) async def renew_token( response: Response, user: dict = Depends(verify_token), x_api_key: str = Header(None), ): response.headers["x-api-key"] = x_api_key return {"verified": True, "user": user["email"]} @router.put("/login", tags=["token"]) async def renew_token(response: Response, user: dict = Depends(verify_token)):
import secrets from fastapi import HTTPException, Security, status from fastapi.security import APIKeyHeader API_KEY_HEADER = APIKeyHeader(name="X-API-Key") class ApiKeyManager: KEY = secrets.token_urlsafe() @classmethod def verify(cls, api_key_header: str = Security(API_KEY_HEADER)) -> None: if api_key_header != cls.KEY: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
from fastapi import HTTPException from fastapi.params import Security from fastapi.security import APIKeyHeader from server.exception.exception import LoginException from server.services.firebase_service import FirebaseService x_api_key_header = APIKeyHeader(name="x-api-key", auto_error=False) def get_token(api_key_header: str = Security(x_api_key_header)): if not api_key_header: raise HTTPException(status_code=401, detail="token header invalid") fb_service = FirebaseService() if not fb_service.validate_token(api_key_header): raise LoginException(message='Invalid token')
import json from app.settings import JWKS from fastapi import APIRouter, Depends, HTTPException from fastapi.security import APIKeyHeader import jwt router = APIRouter() api_key = APIKeyHeader(name="Authorization", auto_error=False) async def authorize_user(authorization: str = Depends(api_key)): credentials_exception = HTTPException( status_code=401, detail="Could not validate token", headers={"WWW-Authenticate": authorization}, ) if authorization: auth = authorization.split(" ") if len(auth) != 2: raise credentials_exception if auth[0] != "Bearer": raise credentials_exception id_token = auth[1] public_key = jwt.algorithms.RSAAlgorithm.from_jwk( json.dumps(JWKS["keys"][0])) try: payload = jwt.decode(id_token,
from fastapi import Security, HTTPException from fastapi.security import APIKeyHeader from app.config import config from starlette.status import HTTP_403_FORBIDDEN apikey_scheme = APIKeyHeader(name=config.APIKEY_HEADER_NAME) def check_token(token: str = Security(apikey_scheme)): if token != config.APIKEY_HEADER_TOKEN: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Access Forbidden") return True
from fastapi import Security from fastapi.security import APIKeyQuery, APIKeyHeader from starlette.exceptions import HTTPException from starlette.status import HTTP_403_FORBIDDEN from fastapi_simple_security._sqlite_access import sqlite_access API_KEY_NAME = "api_key" api_key_query = APIKeyQuery(name=API_KEY_NAME, scheme_name="API key query", auto_error=False) api_key_header = APIKeyHeader(name=API_KEY_NAME, scheme_name="API key header", auto_error=False) async def api_key_security( query_param: str = Security(api_key_query), header_param: str = Security(api_key_header), ): if not query_param and not header_param: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="An API key must be passed as query or header") elif query_param and sqlite_access.check_key(query_param): return query_param elif header_param and sqlite_access.check_key(header_param): return header_param
from fastapi import Depends, HTTPException from fastapi.security import APIKeyHeader import jwt from filler.core.schemas import User from filler.core.settings import settings token_scheme = APIKeyHeader(name="Token", auto_error=False) async def verify_token(token: str = Depends(token_scheme)): if not token: raise HTTPException(403, {"error": "Ошибка доступа"}) try: data = jwt.decode(token, settings.secret_key, algorithms=["HS256"]) user_id = data["sub"]["user_id"] user_login = data["sub"]["user_login"] except jwt.ExpiredSignatureError: raise HTTPException(403, {"error": "Истёкшая сессия"}) except (jwt.InvalidTokenError, KeyError): raise HTTPException(403, {"error": "Ошибка доступа"}) except Exception: raise HTTPException(500, {"error": "Server error"}) return User(id=user_id, login=user_login)
from typing import Optional import uvicorn from fastapi import FastAPI, Depends from fastapi.security import APIKeyHeader from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.cors import CORSMiddleware from app.common.consts import EXCEPT_PATH_LIST, EXCEPT_PATH_REGEX from app.database.conn import db from app.common.config import conf from app.middlewares.token_validator import access_control from app.middlewares.trusted_hosts import TrustedHostMiddleware from app.routes import index, auth, users, services API_KEY_HEADER = APIKeyHeader(name="Authorization", auto_error=False) def create_app(): """ 앱 함수 실행 :return: """ c = conf() app = FastAPI() conf_dict = asdict(c) db.init_app(app, **conf_dict) # 데이터 베이스 이니셜라이즈 # 레디스 이니셜라이즈
from fastapi import Depends from fastapi.security import APIKeyHeader X_API_KEY = APIKeyHeader(name='X-API-Key') def build_check_authentication_header(api_key: str): def check_authentication_header(x_api_key: str = Depends(X_API_KEY)): """ takes the X-API-Key header and converts it into the matching user object from the database """ if x_api_key == api_key: return True else: return False return check_authentication_header
"farm.assets": "Access assets", "farm.terms": "Access terms", "farm.areas": "Access areas", } optional_oauth2 = OAuth2PasswordBearer( tokenUrl=f"{settings.API_V1_STR}/login/access-token", scopes=oauth_scopes, auto_error=False) reusable_oauth2 = OAuth2PasswordBearer( tokenUrl=f"{settings.API_V1_STR}/login/access-token", scopes=oauth_scopes, auto_error=True) API_KEY_NAME = "api-token" api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) def get_current_user(security_scopes: SecurityScopes, db: Session = Depends(get_db), token: str = Security(reusable_oauth2)): if security_scopes.scopes: authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' else: authenticate_value = f"Bearer" credentials_exception = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": authenticate_value}, )