Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用客户端ID实现OAuth到FastAPI;秘密_Python_Oauth 2.0_Fastapi - Fatal编程技术网

Python 如何使用客户端ID实现OAuth到FastAPI;秘密

Python 如何使用客户端ID实现OAuth到FastAPI;秘密,python,oauth-2.0,fastapi,Python,Oauth 2.0,Fastapi,我已经阅读了关于Oauth2的文档,但它没有描述添加客户机id和密码的过程 这是怎么回事 class UserInDB(User): hashed_password: str 从文档中的原始示例来看,它使用了OAuth2PasswordRequestForm来验证用户身份。这个类基本上有6个不同的字段 grant_type: str = Form(None, regex="password"), username: str = Form(...), passwor

我已经阅读了关于Oauth2的文档,但它没有描述添加客户机id和密码的过程

这是怎么回事

class UserInDB(User):
    hashed_password: str

从文档中的原始示例来看,它使用了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),
因此,如果您对此处感兴趣,您可以添加
客户id
客户机密

但我通常更喜欢,它节省了很多时间,使它更容易。下面是如何使用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'
    }
)
我们不需要在这里添加client_id和client_secret,因为它们位于.env文件中。你不应该在真实产品的代码中硬编码它们。谷歌有一个OpenID发现端点,我们可以将此URL用于
server\u metadata\u URL
。Authlib将自动获取此
服务器\u元数据\u url
,以便为您配置OAuth客户端

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

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

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret-string")
我们需要这个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
当您从Google网站授予访问权限时,Google将重定向回您给定的
redirect\u uri
,即('auth')的
request.url\u

上述代码将获得一个令牌,该令牌包含访问令牌和id令牌。id_令牌包含用户信息,我们只需对其进行解析即可获得登录用户的信息

资料来源:

如果你还想使用纯FastAPI,请检查此链接

@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