如何使用客户端 ID 和密钥对 FastAPI 实施 OAuth

mik*_*sth 11 python oauth-2.0 fastapi

我已关注有关 Oauth2 的文档,但它没有描述添加客户端 id 和密钥的过程

https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/

这是做什么的

class UserInDB(User):
    hashed_password: str
Run Code Online (Sandbox Code Playgroud)

从原来的例子

Yag*_*nci 11

在文档中,它用于OAuth2PasswordRequestForm对用户进行身份验证,该类基本上有 6 个不同的字段,

grant_type: str = Form(None, regex="password"),
username: str = Form(...),
password: str = Form(...),
scope: str = Form(""),
client_id: Optional[str] = Form(None),
client_secret: Optional[str] = Form(None),
Run Code Online (Sandbox Code Playgroud)

因此,如果您有兴趣,可以在此处添加client_id存储库client_secret

但我通常更喜欢authlib,它节省了很多时间,让事情变得更容易。以下是如何使用 authlib 创建 OAuth 的完整示例

首先创建一个OAuth客户端

from authlib.integrations.starlette_client import OAuth
from starlette.config import Config

config = Config('.env')  # read config from .env file
oauth = OAuth(config)
oauth.register(
    name='google',
    server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
    client_kwargs={
        'scope': 'openid email profile'
    }
)
Run Code Online (Sandbox Code Playgroud)

我们不需要在这里添加 client_id 和 client_secret ,因为它们位于 .env 文件中。您不应该将它们硬编码到实际产品的代码中。Google 有一个 OpenID 发现端点,我们可以将此 URL 用于server_metadata_url. Authlib 将自动获取此信息server_metadata_url来为您配置 OAuth 客户端。

现在我们将创建一个 FastAPI 应用程序来定义登录路由。

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret-string")
Run Code Online (Sandbox Code Playgroud)

我们需要这个 SessionMiddleware,因为 Authlib 将用来request.session存储临时代码和状态。下面的代码是/login端点,会将您重定向到 Google 帐户网站。

@app.route('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri
Run Code Online (Sandbox Code Playgroud)

当您授予 Google 网站访问权限时,Google 将重定向回您指定的redirect_uri,即request.url_for('auth')

@app.route('/auth')
async def auth(request: Request):
    token = await oauth.google.authorize_access_token(request)
    user = await oauth.google.parse_id_token(request, token)
    return user
Run Code Online (Sandbox Code Playgroud)

上述代码将获取一个包含access_token和id_token的token。id_token包含用户信息,我们只需解析它即可获取登录用户的信息。

来源:Authlib-FastAPI-Google-Login

另外,如果您仍然想使用 Pure FastAPI,请检查此链接FastAPI OAuth2PasswordRequestForm