Hub Python Library documentation

OAuth 和 FastAPI

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

OAuth 和 FastAPI

OAuth 是一种用于访问委托的开放标准,通常用于在无需暴露用户凭据的情况下,授予应用程序对用户信息的有限访问权限。与 FastAPI 结合使用时,它可以让你构建安全的 API,允许用户使用 Google 或 GitHub 等外部身份提供商登录。 在典型场景中:

  • FastAPI 将定义 API 端点并处理 HTTP 请求。
  • OAuth 通过 fastapi.security 等库或 Authlib 等外部工具进行集成。
  • 当用户想要登录时,FastAPI 会将他们重定向到 OAuth 提供方的登录页面。
  • 成功登录后,提供商会携带令牌重定向回原页面。
  • FastAPI 会验证此令牌,并使用它来授权用户或获取用户个人资料数据。

这种方法有助于避免直接处理密码,并将身份验证管理委托给受信任的提供商。

FastAPI 中的 Hugging Face OAuth 集成

该模块提供了将 Hugging Face OAuth 集成到 FastAPI 应用程序中的工具。它支持使用 Hugging Face 平台进行用户身份验证,包括用于本地开发的模拟行为以及用于 Spaces 的真实 OAuth 流程。

OAuth 概述

attach_huggingface_oauth 函数会为 FastAPI 应用添加登录、登出和回调端点。在 Space 中使用时,它会连接到 Hugging Face OAuth 系统。在本地使用时,它会注入一个模拟用户。点击此处了解如何在 Space 中添加“使用 HF 登录”选项

如何使用?

from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
from fastapi import FastAPI, Request

app = FastAPI()
attach_huggingface_oauth(app)

@app.get("/")
def greet_json(request: Request):
    oauth_info = parse_huggingface_oauth(request)
    if oauth_info is None:
        return {"msg": "Not logged in!"}
    return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}

您可能还会对一个展示 OAuth 实际应用的实用示例感兴趣。 如需更全面的实现,请查看medoidai/GiveBackGPT Space,该 Space 在一个完整规模的应用中实现了 HF OAuth。

attach_huggingface_oauth

huggingface_hub.attach_huggingface_oauth

< >

( app: fastapi.FastAPIroute_prefix: str = '/' )

在 FastAPI 应用中添加 OAuth 端点,以启用通过 Hugging Face 进行 OAuth 登录。

如何使用:

  • 在您的 FastAPI 应用上调用此方法以添加 OAuth 端点。
  • 在路由处理程序中,调用 parse_huggingface_oauth(request) 以获取 OAuth 信息。
  • 如果用户已登录,则返回包含用户信息的 OAuthInfo 对象。否则,返回 None。
  • 在您的应用中,请确保添加指向 /oauth/huggingface/login 和 /oauth/huggingface/logout 的链接,以便用户登录和登出。

示例:

from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth

# Create a FastAPI app
app = FastAPI()

# Add OAuth endpoints to the FastAPI app
attach_huggingface_oauth(app)

# Add a route that greets the user if they are logged in
@app.get("/")
def greet_json(request: Request):
    # Retrieve the OAuth info from the request
    oauth_info = parse_huggingface_oauth(request)  # e.g. OAuthInfo dataclass
    if oauth_info is None:
        return {"msg": "Not logged in!"}
    return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}

parse_huggingface_oauth

huggingface_hub.parse_huggingface_oauth

< >

( request: fastapi.Request )

以 OAuthInfo 对象的形式返回已登录用户的信息。

为了灵活性和面向未来的设计,此方法在解析时非常宽松,不会引发错误。 缺失的字段会被设置为 None,且不会发出警告。

如果用户未登录(会话 cookie 中没有信息),则返回 None。

有关如何使用此方法的示例,请参阅 attach_huggingface_oauth()。

OAuthOrgInfo

类 huggingface_hub.OAuthOrgInfo

< >

( sub: strname: strpreferred_username: strpicture: strplan: str | None = Nonecan_pay: bool | None = Nonerole_in_org: str | None = Nonesecurity_restrictions: list[typing.Literal['ip', 'token-policy', 'mfa', 'sso']] | None = None )

参数

  • sub (str) — 组织的唯一标识符。OpenID Connect 字段。
  • name (str) — 该组织的完整名称。OpenID Connect 字段。
  • preferred_username (str) — 组织的用户名。OpenID Connect 字段。
  • picture (str) — 该组织的头像图片 URL。OpenID Connect 字段。
  • plan (str, 可选) — 该组织的计划(例如,“enterprise”、“team”)。Hugging Face 字段。
  • can_pay (Optional[bool],可选) — 该组织是否已设置付款方式。Hugging Face 字段。
  • role_in_org (Optional[str],可选) — 用户在组织中的角色。Hugging Face 字段。
  • security_restrictions (Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]], 可选) — 用户在此组织中尚未完成的安全限制数组。可能的值:“ip”、“token-policy”、“mfa”、“sso”。Hugging Face 字段。

与通过 OAuth 登录的用户关联的组织信息。

OAuthUserInfo

类 huggingface_hub.OAuthUserInfo

< >

( sub: strname: strpreferred_username: stremail_verified: bool | Noneemail: str | Nonepicture: strprofile: strwebsite: str | Noneis_pro: boolcan_pay: bool | Noneorgs: list[huggingface_hub._oauth.OAuthOrgInfo] | None )

参数

  • sub (str) — 用户的唯一标识符,即使用户名更改也不会改变。OpenID Connect 字段。
  • name (str) — 用户的完整姓名。OpenID Connect 字段。
  • preferred_username (str) — 用户的用户名。OpenID Connect 字段。
  • email_verified (Optional[bool],可选) — 指示用户的电子邮件是否已验证。OpenID Connect 字段。
  • email (Optional[str], 可选) — 用户的电子邮件地址。OpenID Connect 字段。
  • picture (str) — 用户的个人资料图片 URL。OpenID Connect 字段。
  • profile (str) — 用户的个人资料 URL。OpenID Connect 字段。
  • website (Optional[str], 可选) — 用户的网站 URL。OpenID Connect 字段。
  • is_pro (bool) — 用户是否为专业用户。Hugging Face 字段。
  • can_pay (Optional[bool],可选) — 用户是否已设置支付方式。Hugging Face 字段。
  • orgs (Optional[list[OrgInfo]],可选) — 用户所属的组织列表。Hugging Face 字段。

通过 OAuth 登录的用户信息。

OAuthInfo

类 huggingface_hub.OAuthInfo

< >

( access_token: straccess_token_expires_at: datetimeuser_info: OAuthUserInfostate: str | Nonescope: str )

参数

  • access_token (str) — 访问令牌。
  • access_token_expires_at (datetime.datetime) — 访问令牌的过期时间。
  • user_info (OAuthUserInfo) — 用户信息。
  • state (str, 可选) — 在最初向 OAuth 提供商发起请求时,传递给该 OAuth 提供商的状态。
  • scope (str) — 授予的作用域。

有关 OAuth 登录的信息。

Update on GitHub