使用 clientid/clientsecret 验证 FastAPI

Authenticate FastAPI with clientid/clientsecret

我正在尝试使用 clientid-clientsecret 设置快速API (0.71.0) 身份验证。

我配置了 OAuth2AuthorizationCodeBearer,显然从 swagger (/docs) 端点来看它看起来不错,它要求提供 client-id 和 client-secret 进行身份验证。

auth = OAuth2PasswordBearer(
    authorizationUrl=AUTH_URL,
    tokenUrl=TOKEN_URL,
)

agent = FastAPI(
    description=_DESCRIPTION,
    version=VERSION,
    dependencies=[Depends(auth)],
    middleware=middlewares,
    root_path=os.getenv('BASEPATH', '/'),
    swagger_ui_init_oauth={
        'usePkceWithAuthorizationCodeGrant': True,
        'scopes': 'openid profile email'
    }
)

但是直接调用 API 我可以使用任何 Bearer 访问,例如:

import requests

url = 'http://localhost:8080/test'
headers = {'Authorization': 'Bearer BADTOKEN', 'Content-Type': 'application/json', 'Accept': 'application/json'}
response = requests.get(url=url, params={}, headers=headers)

response.ok = True,所以我可能在 FastAPI 设置中遗漏了一些东西,但看不到哪里。

这是正确的身份验证流程吗?

PS: What I want to achieve is service to service communication, so the API is not getting accessed by a regular user

看了 OAuth2AuthorizationCodeBearer implementation 之后,我最后添加了一个方法来检查不记名令牌的有效性:

public_key = requests.get(ISSUER_URL).json().get('public_key')
key = '-----BEGIN PUBLIC KEY-----\n' + public_key + '\n-----END PUBLIC KEY-----'

oauth = OAuth2AuthorizationCodeBearer(
        authorizationUrl=AUTH_URL,
        tokenUrl=TOKEN_URL,
)
async def auth(token: str | None = Depends(oauth)):
    try:
        jwt.decode(
            token,
            key=key,
            options={
                "verify_signature": True,
                "verify_aud": False,
                "verify_iss": ISSUER_URL
            }
        )
    except JOSEError as e:  # catches any exception
        raise HTTPException(
            status_code=401,
            detail=str(e))