首页 > 其他分享 >Adding API Key Authentication to a FastAPI application

Adding API Key Authentication to a FastAPI application

时间:2023-09-15 16:33:24浏览次数:59  
标签:API Adding header FastAPI application api key query Security

https://joshdimella.com/blog/adding-api-key-auth-to-fast-api

Step 1: Define a List of Valid API Keys

API_KEYS = [
    "9d207bf0-10f5-4d8f-a479-22ff5aeff8d1",
    "f47d4a2c-24cf-4745-937e-620a5963c0b8",
    "b7061546-75e8-444b-a2c4-f19655d07eb8",
]

Step 2: Implement API Key Security Function

from fastapi import HTTPException, status, Security, FastAPI
from fastapi.security import APIKeyHeader, APIKeyQuery

api_key_query = APIKeyQuery(name="api-key", auto_error=False)
api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)

def get_api_key(
    api_key_query: str = Security(api_key_query),
    api_key_header: str = Security(api_key_header),
) -> str:
    """Retrieve and validate an API key from the query parameters or HTTP header.

    Args:
        api_key_query: The API key passed as a query parameter.
        api_key_header: The API key passed in the HTTP header.

    Returns:
        The validated API key.

    Raises:
        HTTPException: If the API key is invalid or missing.
    """
    if api_key_query in API_KEYS:
        return api_key_query
    if api_key_header in API_KEYS:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

Step 3: Secure the Routes

app = FastAPI()

@app.get("/public")
def public():
    """A public endpoint that does not require any authentication."""
    return "Public Endpoint"

@app.get("/private")
def private(api_key: str = Security(get_api_key)):
    """A private endpoint that requires a valid API key to be provided."""
    return f"Private Endpoint. API Key: {api_key}"

Complete Example

from fastapi import HTTPException, status, Security, FastAPI
from fastapi.security import APIKeyHeader, APIKeyQuery

API_KEYS = [
    "9d207bf0-10f5-4d8f-a479-22ff5aeff8d1",
    "f47d4a2c-24cf-4745-937e-620a5963c0b8",
    "b7061546-75e8-444b-a2c4-f19655d07eb8",
]

api_key_query = APIKeyQuery(name="api-key", auto_error=False)
api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)

def get_api_key(
    api_key_query: str = Security(api_key_query),
    api_key_header: str = Security(api_key_header),
) -> str:
    """Retrieve and validate an API key from the query parameters or HTTP header.

    Args:
        api_key_query: The API key passed as a query parameter.
        api_key_header: The API key passed in the HTTP header.

    Returns:
        The validated API key.

    Raises:
        HTTPException: If the API key is invalid or missing.
    """
    if api_key_query in API_KEYS:
        return api_key_query
    if api_key_header in API_KEYS:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

app = FastAPI()

@app.get("/public")
def public():
    """A public endpoint that does not require any authentication."""
    return "Public Endpoint"

@app.get("/private")
def private(api_key: str = Security(get_api_key)):
    """A private endpoint that requires a valid API key to be provided."""
    return f"Private Endpoint. API Key: {api_key}"

标签:API,Adding,header,FastAPI,application,api,key,query,Security
From: https://www.cnblogs.com/bitterteaer/p/17705337.html

相关文章

  • Laravel 执行流程(三)之 探索 Application 构造函数
    备注:纯手打的学习笔记,如有错误之处请指正,谢谢。希望大家学的开心!说明:本来应该是说Container类(下)的,不过经过学习,直接看这个类实在不好理解,一会是绑定,一会共享实例,真心不知道说的什么....还是先从程序的入口处,顺藤摸瓜,用到的时候再结合上下文理解,比较容易消化,希望理解,抱歉!OK,从入......
  • 获取JavaApplication当前工程路径
    前日因工作中使用到日志和配置工具类,使相关信息输出文件中,因此总结了一下java中获取当前路径的方法(非web工程)。1、File类:Filefile=newFile(".");System.out.println(file.getCanonicalPath());//如果是..则返回上一级文件夹System.out.println(file.getAbsolut......
  • fastapi设置响应示例
    classTest(BaseModel):name:strdescription:intcreated_at:strupdated_at:strdata:dict@validator("data",pre=True)defparse_data(cls,value):returnjson.loads(value)ifvalueelse{}@validator(......
  • JMS connection pools and sessions pools in WebSphere Application Server
    转载:[url]http://www-01.ibm.com/support/docview.wss?uid=swg21168924QuestionFrequentlyAskedQuestionsconcerningconnectionpoolsandsessionspoolsinIBM®WebSphere®ApplicationServer.AnswerQ:WebSphereMQQueueConnectionFactoriesinWebSphere......
  • 使用 SAP Business Application Studio Data Editor 生成 Mock Data
    SAPBusinessTechnologyPlatform(BTP)是SAP提供的一种综合性云平台,用于构建、扩展和集成企业应用程序。它为企业提供了一个强大的工具集,以支持数字转型和业务创新。在BTP上,BusinessApplicationStudio(BAS)是一个云集成开发环境,它为开发人员提供了一种轻松创建、管理和......
  • FastAPI学习-12. 请求Cookie 参数
    前言你可以像定义 Query 参数和 Path 参数一样来定义 Cookie 参数。声明 Cookie 参数首先,导入 Cookie:fromfastapiimportCookie,FastAPI声明 Cookie 参数的结构与声明 Query 参数和 Path 参数时相同。第一个值是参数的默认值,同时也可以传递所有验证参数......
  • application 'vueApp' died in status NOT_MOUNTED: [qiankun]: Target container wit
    这是第一次微前端很常见的提示,尤其是第一次写前端的时候碰到的解决1:主应用的 App.vue标签上的id="app"去掉,这是报错的根本解决2://在子应用挂在的时候处理functionrender(props={}){const{container}=props;instance=newVue({render:h=>h......
  • Java安全架构____RSA加密配置第三方加密库问题_javax.crypto.BadPaddingException: De
    刚要写一个JCE组件是未使用第三方加密库时bug如下javax.crypto.BadPaddingException:Decryptionerroratsun.security.rsa.RSAPadding.unpadV15(UnknownSource)atsun.security.rsa.RSAPadding.unpad(UnknownSource)atcom.sun.crypto.provider.RSACipher.doFinal(RSACipher.j......
  • 在线问诊 Python、FastAPI、Neo4j — 创建症状节点
    目录参考创建药品节点。importloggingfromutils.neo4j_providerimportdriverlogging.root.setLevel(logging.INFO)#并生成CQLdefgenerate_cql()->str:cql="""CREATE(symptom1:Symptom{name:"膝盖疼"}),(symptom2......
  • FastAPI 参数体检RequestBody
    一、概述一般对于RequestBody不会通过get提交,对于get提交的参数一般称为是查询参数。所以,如果是通过POTS,PUT等方式提交的参数信息,我们一般是放到RequestBody来提交到我们的后端。对于如何接收和校验请求体,FastApi提供的形式是使用:frompydanticimportBaseModel示例如下:im......