def get_token(token: str = Security(APIKeyQuery(name="token", auto_error=True))): """Get token from query parameters and test against known TOKEN. Parameters ---------- token : str Returns ------- str returns token if it matches known TOKEN, otherwise raises HTTPException. """ if token == API_TOKEN: return token raise HTTPException(status_code=403, detail="Invalid token")
from fastapi.params import Body 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
return None if scheme.lower() != "apikey": raise HTTPException( status_code=400, detail=( "Authorization header must include the authorization type " "followed by a space and then the secret, as in " "'Bearer SECRET' or 'Apikey SECRET'. " ), ) return param # The tokenUrl below is patched at app startup when we know it. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="PLACEHOLDER", auto_error=False) api_key_query = APIKeyQuery(name="api_key", auto_error=False) api_key_header = APIKeyAuthorizationHeader( name="Authorization", description="Prefix value with 'Apikey ' as in, 'Apikey SECRET'", ) api_key_cookie = APIKeyCookie(name=API_KEY_COOKIE_NAME, auto_error=False) def create_access_token(data, secret_key, expires_delta): to_encode = data.copy() expire = utcnow() + expires_delta to_encode.update({"exp": expire, "type": "access"}) encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=ALGORITHM) return encoded_jwt
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:
def __init__(self, api_key: str = Security(APIKeyQuery(name='api_key'))): if not secure_strings_same(api_key, service_config.api_key): raise NotAuthenticated403()
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(
from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException from fastapi.security.api_key import APIKeyQuery, APIKey from pydantic import BaseModel from starlette.status import HTTP_403_FORBIDDEN from skimage.metrics import structural_similarity as ssim import cv2 import numpy as np import requests as re API_KEY = "6e8e8295-cfa1-4bb7-9ea6-c15df77e11e2" API_KEY_NAME = 'access_token' api_key_query = APIKeyQuery(name=API_KEY_NAME) app = FastAPI() # define function for retrieving API key from query parameter async def get_api_key(api_key_query: str = Security(api_key_query)): if api_key_query == API_KEY: return api_key_query else: raise HTTPException(status_cod=HTTP_403_FORBIDDEN, detail="Could not validate credentials") # pydantic offers BaseModel class for request body declaration/validation class Urls(BaseModel):
""" 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(
# coding: utf-8 import hashlib from fastapi import Security, HTTPException, status, Depends from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader from sqlalchemy import select from sqlalchemy.sql import bindparam from core.pydantic_models import UserInDB from core.setting import get_setting, redisDBenum from db.connector import db, get_redis from db.models.user import user access_token_query = APIKeyQuery(name="access_token", auto_error=False) access_token_header = APIKeyHeader(name="access_token", auto_error=False) access_token_cookie = APIKeyCookie(name="access_token", auto_error=False) def hash_password(password: str) -> str: temp_hash = password for _ in range(10000): temp_hash = hashlib.sha512(temp_hash.encode("utf-8")).hexdigest() return temp_hash async def get_access_token( access_token_query: str = Security(access_token_query), access_token_header: str = Security(access_token_header), access_token_cookie: str = Security(access_token_cookie), ):
"http://127.0.0.1:8080", "http://localhost", "http://*****:*****@app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time)
import os from dotenv import load_dotenv, find_dotenv from fastapi.security.api_key import APIKeyQuery load_dotenv(find_dotenv()) API_KEY = os.environ["API_KEY"] API_KEY_NAME = "api_key" API_KEY_QUERY = APIKeyQuery(name=API_KEY_NAME, auto_error=True)
from fastapi import FastAPI import requests import mimetypes import os from pydantic import BaseModel from fastapi import Security, Depends, FastAPI, HTTPException from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader, APIKey from starlette.status import HTTP_403_FORBIDDEN, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_400_BAD_REQUEST from starlette.responses import RedirectResponse, JSONResponse import urllib.request from open_nsfw_python3 import NSFWClassifier import os from time import time API_KEY = "1234567asdfgh" api_key_query = APIKeyQuery(name='api_key', auto_error=False) app = FastAPI() global classifier, folder_to_write classifier = NSFWClassifier() folder_to_write = '/app/data' class Image_Url(BaseModel): image_url: str # Download image function def download_img(url): supported_types = ['image/jpe', 'image/jpeg', 'image/jpg', 'image/png'] start = time()
class Args: @classmethod def create(cls, params): params_str = ",".join(f"{k}: Optional[{params[k]}]" for k in params) exec(f"def fn(self, {params_str}): pass;\ncls.__init__ = fn") return cls def endpoint_post(endpoint_name, endpoint_params): print(f"{endpoint_name}:") for k in endpoint_params: print(f"{k}: {endpoint_params[k]}") api_key_query = APIKeyQuery(name="api_key") async def get_api_key(api_key_query: str = Security(api_key_query)): if api_key_query == API_KEY: return api_key_query else: raise HTTPException(status_code=403) app = FastAPI() @app.on_event("startup") async def startup(): await DATABASE.connect()
from fastapi import HTTPException from fastapi import Security from fastapi import status from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.security.api_key import APIKeyQuery from .client import get_client from .models import User ### Endpoints can require authentication using Depends(get_current_user) ### get_current_user will look for a token in url params or ### Authorization: bearer token (header). ### Hub technically supports cookie auth too, but it is deprecated so ### not being included here. auth_by_param = APIKeyQuery(name="token", auto_error=False) auth_url = os.environ["PUBLIC_HOST"] + "/hub/api/oauth2/authorize" auth_by_header = OAuth2AuthorizationCodeBearer(authorizationUrl=auth_url, tokenUrl="get_token", auto_error=False) ### ^^ The flow for OAuth2 in Swagger is that the "authorize" button ### will redirect user (browser) to "auth_url", which is the Hub login page. ### After logging in, the browser will POST to our internal /get_token endpoint ### with the auth code. That endpoint POST's to Hub /oauth2/token with ### our client_secret (JUPYTERHUB_API_TOKEN) and that code to get an ### access_token, which it returns to browser, which places in Authorization header. if os.environ.get("JUPYTERHUB_OAUTH_SCOPES"): # typically ["access:services", "access:services!service=$service_name"] access_scopes = json.loads(os.environ["JUPYTERHUB_OAUTH_SCOPES"])