async def validate_api_key(api_key: str = Security( APIKeyHeader(name="Authorization"))): """Validate the API_KEY as delivered by the Authorization header It is recommended to always set a unique XLWINGS_API_KEY as environment variable. Without an env var, it expects "DEVELOPMENT" as the API_KEY, which is insecure. """ if api_key != os.getenv("XLWINGS_API_KEY", "DEVELOPMENT"): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API Key", )
class APITokenMiddleware(BaseHTTPMiddleware): # Define API X_API_KEY = APIKeyHeader(name='X-API-Key') async def dispatch(self, request: Request, call_next) -> Response: try: key = await self.X_API_KEY(request) except HTTPException: return Response(status_code=403) response = await call_next(request) return response
def get_api_key(optional = False): api_key_header = APIKeyHeader(name = 'X-API-Key', auto_error = not optional) def validate_api_key(request: Request, api_key: Optional[str] = Security(api_key_header)): config = request.app.state.context['configuration'] if api_key is None: return None elif api_key == config.get('API_ACCESS_KEY'): return api_key else: raise exceptions.invalid_api_key return Depends(validate_api_key)
def api_key(key: str = Depends(APIKeyHeader(name=API_KEY_HEADER_NAME))) -> str: """Validate an api key string matches the value currently in SecretsManager""" region = APIServiceConfig().region current_api_key_secret = get_api_key(region_name=region) if key == current_api_key_secret: return key try: pending_api_key_secret = get_api_key(version_stage="AWSPENDING", region_name=region) if key == pending_api_key_secret: return key except ClientError as c_e: response_error = getattr(c_e, "response", {}).get("Error", {}) error_code = response_error.get("Code", "") if error_code != "ResourceNotFoundException": raise c_e raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials")
def get_token_api_key( token_api_key_header: str = Security( APIKeyHeader(name="api_key", auto_error=False)), ) -> TokenModel: """ Check and retrieve authentication information from api_key. :param token_api_key_header API key provided by Authorization[api_key] header :type token_api_key_header: str :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API :rtype: TokenModel | None """ ...
""" from datetime import datetime, timedelta from fastapi import Request from fastapi.security.api_key import APIKeyHeader from jose import jwt, JWTError from passlib.context import CryptContext from users.models import User from config import settings # Password manage pwd_context = CryptContext(schemes=["bcrypt"]) # Token extracter auth_schema = APIKeyHeader(name="Authorization") # ******************************* # Auth helpers * # ******************************* class Security: """ Class for manage security tasks. """ def raise_invalid_credentials_exception(self) -> None: """ Raise a aunauthorized exception and interrump the request process. """
from fastapi import Depends, HTTPException, Security from fastapi.security.api_key import APIKeyHeader from starlette.status import HTTP_403_FORBIDDEN from app.settings import Settings, get_settings API_KEY_HEADER = APIKeyHeader(name="x-api-key") def api_key_checker( api_key: str = Security(API_KEY_HEADER), settings: Settings = Depends(get_settings), ): if api_key != settings.API_KEY.get_secret_value(): raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials")
import secrets from typing import Optional from fastapi import HTTPException, Security from fastapi.security.api_key import APIKeyHeader from backend.core import settings from backend.core.messages import AUTH_REQ, NO_API_KEY api_key_handler = APIKeyHeader(name="token", auto_error=False) def validate_request(header: Optional[str] = Security(api_key_handler)): if header is None: raise HTTPException(status_code=400, detail=NO_API_KEY, headers={}) if not secrets.compare_digest(header, str(settings.auth_key)): raise HTTPException(status_code=401, detail=AUTH_REQ, headers={}) return True
from fastapi.params import Depends from fastapi.params import Security from fastapi.responses import JSONResponse from fastapi.security.api_key import APIKey from fastapi.security.api_key import APIKeyCookie from fastapi.security.api_key import APIKeyHeader from fastapi.security.api_key import APIKeyQuery from starlette.status import HTTP_401_UNAUTHORIZED router = APIRouter() API_KEY = getenv("WEB_API_KEY") API_KEY_NAME = "access_token" api_key_query = APIKeyQuery(name=API_KEY_NAME, auto_error=False) api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) api_key_cookie = APIKeyCookie(name=API_KEY_NAME, auto_error=False) async def get_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), api_key_cookie: str = Security(api_key_cookie), ): if api_key_query == API_KEY: return api_key_query elif api_key_header == API_KEY: return api_key_header elif api_key_cookie == API_KEY: return api_key_cookie else:
from . import config # https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680 from fastapi import Security, Depends, FastAPI, HTTPException from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader, APIKey from starlette.status import HTTP_403_FORBIDDEN api_key_query = APIKeyQuery(name=config.Settings().api_key_name, auto_error=False) api_key_header = APIKeyHeader(name=config.Settings().api_key_name, auto_error=False) api_key_cookie = APIKeyCookie(name=config.Settings().api_key_name, auto_error=False) async def get_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), api_key_cookie: str = Security(api_key_cookie), ): api_tokens = config.Settings().api_tokens org = api_tokens.get(api_key_query) if org is not None: return org org = api_tokens.get(api_key_header) if org is not None: return org # since we are storing org in cookie, let us do a reverse # map lookup to see if there is a key for this org; only # for cookies if api_key_cookie is None:
from fastapi import FastAPI, File, UploadFile, Header, HTTPException, Depends from fastapi.security.api_key import APIKeyHeader import uvicorn from pydantic import BaseModel import hashlib from db import Database app = FastAPI() database = Database('carbery_db.db') x_auth_user = APIKeyHeader(name="X-Auth-User", auto_error=False) class FileHash(BaseModel): userId: str filename: str sha256: str md5: str async def check_auth(x_auth_user: str = Depends(x_auth_user)): if not x_auth_user: raise HTTPException(status_code=401, detail='Не авторизован.') return x_auth_user @app.get('/file_hashes/{hash}', response_model=FileHash, summary='Получение имени файла по хэшу.', status_code=200, response_description='OK')
jwt_body = user_info.dict() jwt_body.update({"iat": iat, "exp": exp}) jwt_body["refresh_token"] = refresh_token token = jwt.encode(header=headers, payload=jwt_body, key=settings.PRIVATE_KEY) return str(token, "utf-8") def decode_token(token: str, public_key: _RSAPublicKey) -> UserInfo: payload = jwt.decode(token, public_key) token_data = UserInfo(**payload) return token_data AUTH_HEADER = APIKeyHeader(name="Authorization") async def get_current_user( token: str = Depends(AUTH_HEADER), session: Session = Depends(get_database_session), public_key: _RSAPublicKey = Depends(get_public_key), ) -> UserInDB: user_info = decode_token(token, public_key) user: Optional[User] = session.query(User).filter( User.email == user_info.email).first() if not user or user.disabled: raise UserNotFound return UserInDB( uid=user.uid,
import os import logging from fastapi import Security, HTTPException, status from fastapi.security.api_key import APIKeyHeader API_KEY = os.environ['API_KEY'] API_KEY_NAME = "X-API-KEY" api_key_header_auth = APIKeyHeader(name=API_KEY_NAME, auto_error=True) log = logging.getLogger(__name__) async def get_api_key(api_key_header: str = Security(api_key_header_auth)): if api_key_header != API_KEY: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API Key", ) return api_key_header
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader API_KEY_NAME = "api_key" cookie_scheme = APIKeyCookie(name="bgm-tv-auto-tracker", auto_error=False) API_KEY_HEADER = APIKeyHeader(name="api-key", auto_error=False) API_KEY_COOKIES = APIKeyCookie(name="api-key", auto_error=False)
import datetime from fastapi import HTTPException, Security, status from fastapi.security.api_key import APIKeyHeader from jose import jwt from pydantic import BaseModel, Field from .config import config api_key_security = APIKeyHeader(name="x-api-key") from aioredis import create_redis_pool class User(BaseModel): api_key: str user_id: int = Field(alias="id") rate_limiter: int = Field(alias="rl") random: str = Field(alias="r") redis = None async def init_redis(): global redis if redis is not None: return redis = await create_redis_pool(config.redis_uri)
import os from dotenv import load_dotenv from fastapi import HTTPException, Security, status from fastapi.security.api_key import APIKeyHeader load_dotenv() api_key_header_auth = APIKeyHeader(name='Authorization', auto_error=True) async def get_api_key(api_key_header: str = Security(api_key_header_auth)): """Validate that the request header contains a key named 'Authorization' and that its value matches the DS_SECRET_TOKEN environment variable. See https://github.com/tiangolo/fastapi/issues/142#issuecomment-688566673 """ if api_key_header != os.getenv('DS_SECRET_TOKEN'): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API Key", )
@authors: Leonardo Mauro <leomaurodesenv> @link: https://github.com/leomaurodesenv/data-science-api-framework GitHub @license: MIT License @copyright: 2021 Leonardo Mauro @access: public ''' # FastAPI from fastapi import Security, HTTPException from fastapi.security.api_key import APIKeyHeader # Settings import app.config as config # ---------------------------------------------------------------------- # Security configurations API_KEY_HEADER = APIKeyHeader(name=config.AUTH_KEY_NAME, auto_error=False) # ---------------------------------------------------------------------- # Auxiliar Functions async def api_token(token: str = Security(API_KEY_HEADER)): ''' API authentication token validation @param token: APIKeyHeader object ''' if token == config.AUTH_KEY: return True raise HTTPException(status_code=403, detail="Could not validate the authentication token")
from CommonServerUserPython import * sample_events_to_store = deque(maxlen=20) # type: ignore[var-annotated] class Incident(BaseModel): name: Optional[str] = None type: Optional[str] = None occurred: Optional[str] = None raw_json: Optional[Dict] = None app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) basic_auth = HTTPBasic(auto_error=False) token_auth = APIKeyHeader(auto_error=False, name='Authorization') class GenericWebhookAccessFormatter(AccessFormatter): def get_user_agent(self, scope: Dict) -> str: headers = scope.get('headers', []) user_agent_header = list( filter(lambda header: header[0].decode() == 'user-agent', headers)) user_agent = '' if len(user_agent_header) == 1: user_agent = user_agent_header[0][1].decode() return user_agent def formatMessage(self, record): recordcopy = copy(record) scope = recordcopy.__dict__['scope']
app = FastAPI() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() ################# Security ##################### api_key_header = APIKeyHeader(name=SECRET_KEY_NAME) async def get_api_key(api_key_header: str = Security(api_key_header)): if api_key_header == SECRET_KEY: return api_key_header else: raise HTTPException(status_code=403, detail="Could not validate credentials") ################### API ######################## client.remove_command("help") @app.on_event("startup")
from fastapi import Request, Security, HTTPException from fastapi.security.api_key import APIKeyHeader from app.database import AccessKey from typing import Optional header_authorization = APIKeyHeader(name="Authorization", auto_error=True) async def get_api_key( request: Request, api_key_header: str = Security(header_authorization) ) -> Optional[AccessKey]: response = await request.state.db.get_access_key_details(api_key_header) if response: return response else: raise HTTPException(status_code=401, detail="Not Authorised / Invalid API Key")
import json import requests import os from fastapi import Security, HTTPException, status from fastapi.security.api_key import APIKeyHeader from functools import wraps from jose import jwt AUTH0_DOMAIN = os.getenv("AUTH0_DOMAIN", "Auth0 Domain undefined") API_AUDIENCE = os.getenv("API_AUDIENCE", "Auth0 Api audience undefined") ALGORITHMS = os.getenv("ALGORITHMS", "Algorithms undefined") api_key = APIKeyHeader(name="authorization") def required_auth(token: str = Security(api_key)): if 'BEARER ' not in token[0:7].upper(): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="""invalid_token: Could not validate credentials""") url_api = f'{AUTH0_DOMAIN}.well-known/jwks.json' jwks = requests.get(url_api).json() token = token.split(' ')[1] try: unverified_header = jwt.get_unverified_header(token) except jose_exceptions.JWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="""invalid_decode_token: Error decoding token headers""") rsa_key = {} for key in jwks["keys"]:
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import hashlib from fastapi import HTTPException, Security, status from fastapi.security.api_key import APIKeyHeader, APIKey from .db import db from . import models query = APIKeyHeader(name="X-API-Key", auto_error=False) InvalidAPIKey = HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials") async def validate_api_key(raw_api_key: APIKey = Security(query)): if not raw_api_key: raise InvalidAPIKey key = hashlib.sha256(raw_api_key.encode("utf-8")).hexdigest() provider = await models.Provider.get_provider_for_key(db, key) if not provider: raise InvalidAPIKey return provider
""" Set up api_key logics https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680 """ from typing import Union from fastapi import HTTPException, Security from fastapi.security.api_key import APIKeyHeader, APIKeyQuery from starlette.status import HTTP_403_FORBIDDEN from app.settings import api_key, api_private_access api_key_name = "api_key" api_key_query = APIKeyQuery(name=api_key_name, auto_error=False) api_key_header = APIKeyHeader(name=api_key_name, auto_error=False) def get_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), ) -> Union[bool, str]: if api_private_access: return True elif api_key_query == api_key: return api_key_query elif api_key_header == api_key: return api_key_header else: raise HTTPException(
from fastapi import Depends, HTTPException, Security from fastapi.security.api_key import APIKeyHeader from starlette.status import HTTP_403_FORBIDDEN from ..config import Settings, get_settings API_KEY_HEADER = APIKeyHeader(name='x-api-key') def api_key_checker( api_key: str = Security(API_KEY_HEADER), settings: Settings = Depends(get_settings), ): if api_key != settings.API_KEY.get_secret_value(): raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail='Could not validate credentials')
user_schema: UserSchema = Body(..., embed=True, alias="user"), session: Session = Depends(get_session), ): user_service = UserService(session) auth_service = AuthenticationService(session) if not user_service.get_by_email(user_schema.email): raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail='E-mail não encontrado' ) try: token = auth_service.get_token( user_schema.email, user_schema.password ) except EmailOrPasswordInvalid: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail='E-mail ou senha inválido' ) return { 'message': 'Login efetuado', 'token': token } api_key_authorization = APIKeyHeader(name='authorization')
class TemperatureDateEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime.datetime): return o.isoformat() elif isinstance(o, TemperatureData): return o.__dict__ return json.JSONEncoder.default(self, o) GLOBAL_DATA: List[TemperatureData] = [] data_lock = threading.Lock() api_key_header = APIKeyHeader(name=API_KEY_NAME) async def get_api_key(header: str = Security(api_key_header)): if header == API_KEY: return header else: raise HTTPException(status_code=starlette.status.HTTP_403_FORBIDDEN, detail='Could not validate credentials') @app.get("/get-temperature") async def get_temperature(): with data_lock: return [[datum.timestamp, datum.temperature] for datum in GLOBAL_DATA]
import secrets from typing import Optional from fastapi import HTTPException, Security from fastapi.security.api_key import APIKeyHeader from starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED from smart_compose.api.core import config from smart_compose.api.core.messages import AUTH_REQ, NO_API_KEY api_key = APIKeyHeader(name="token", auto_error=False) def validate_request(header: Optional[str] = Security(api_key)) -> bool: if header is None: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=NO_API_KEY, headers={}) if not secrets.compare_digest(header, str(config.API_KEY)): raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail=AUTH_REQ, headers={}) return True
from .exceptions import ( BadCredentials, BadCredentialsKeyNotFound, RevokedCredentials, UnauthorizedRequest, ) from .schema import AuthApiKeyRecord from .utils import cookie_name_from_auth_name, header_name_from_auth_name logger = logging.getLogger("opennem.auth") APP_AUTH_COOKIE_NAME = cookie_name_from_auth_name(settings.api_app_auth_name) APP_AUTH_HEADER_NAME = header_name_from_auth_name(settings.api_app_auth_name) api_key_query = APIKeyQuery(name=APP_AUTH_COOKIE_NAME, auto_error=False) api_key_header = APIKeyHeader(name=APP_AUTH_HEADER_NAME, auto_error=False) api_key_cookie = APIKeyCookie(name=APP_AUTH_COOKIE_NAME, auto_error=False) def get_api_key_record(api_key: str) -> AuthApiKeyRecord: """Get an API Key record from the database""" session = get_scoped_session() try: api_key = validate_api_key(api_key) except Exception as e: logger.error("Bad API key {}: {}".format(api_key, e)) raise UnauthorizedRequest() api_key_record: Optional[ApiKeys] = (session.query(ApiKeys).filter_by( keyid=api_key).one_or_none())
from datetime import datetime, timedelta from uuid import uuid4 import bcrypt from fastapi import APIRouter, HTTPException, status, Security, Depends from fastapi.security.api_key import APIKeyHeader from pydantic import BaseModel from controllers.database import database, client from controllers.events import create_event Users = database["users"] Sessions = database["sessions"] Events = database["events"] api_key_header = APIKeyHeader(name="access_token", auto_error=False) router = APIRouter() class Session(BaseModel): username: str token: str expires: datetime class Login(BaseModel): username: str password: str class UserClass(BaseModel):
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader from sqlalchemy.orm import Session from lation.modules.base.models.end_user import EndUser, EndUserToken from lation.modules.base.models.payment import PaymentGateway from lation.modules.base_fastapi.dependencies import get_session from lation.modules.customer.customer import CustomerApp from lation.modules.customer.models.platform import Platform # https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680 access_token_cookie_scheme = APIKeyCookie(scheme_name='Access Token Cookie Scheme', name=CustomerApp.ACCESS_TOKEN_COOKIE_KEY, auto_error=False) access_token_header_scheme = APIKeyHeader(scheme_name='Access Token Header Scheme', name=CustomerApp.ACCESS_TOKEN_HEADER_KEY, auto_error=False) async def get_access_token(access_token_cookie:Optional[str]=Security(access_token_cookie_scheme), access_token_header:Optional[str]=Security(access_token_header_scheme)) -> str: if access_token_cookie: return access_token_cookie elif access_token_header: return access_token_header else: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Access token required') async def login_required(request:Request, access_token:str=Depends(get_access_token), session:Session=Depends(get_session)): end_user_token = session.query(EndUserToken)\ .filter(EndUserToken.value == access_token, EndUserToken.is_active == True)\ .one_or_none() if not end_user_token: