# OAuthとFastAPI

OAuthはアクセス委譲のためのオープン標準であり、ユーザーの認証情報を公開せずにアプリケーションにユーザー情報の限られたアクセス権を付与するために広く使用されています。FastAPIと組み合わせることで、GoogleやGitHubなどの外部アイデンティティプロバイダーを使用してユーザーがログインできる安全なAPIを構築できます。一般的なシナリオでは:
- FastAPI は API エンドポイントを定義し、HTTP リクエストを処理します。
- OAuthは、fastapi.securityのようなライブラリや、Authlibのような外部ツールを使用して統合されます。
- ユーザーがログインを希望すると、FastAPIはユーザーをOAuthプロバイダーのログインページにリダイレクトします。
- ログインが正常に完了すると、プロバイダーはトークン付きでリダイレクトされます。
- FastAPIはこのトークンを検証し、ユーザーの認証またはユーザープロファイルデータの取得に使用します。

このアプローチにより、パスワードを直接処理することを回避し、アイデンティティ管理を信頼できるプロバイダーにオフロードできます。

# FastAPI における Hugging Face OAuth 統合

このモジュールは、FastAPI アプリケーションに Hugging Face OAuth を統合するためのツールを提供します。Hugging Face プラットフォームを使用したユーザー認証を可能にし、ローカル開発用のモック動作と Spaces 用の実際の OAuth フローをサポートします。

## OAuth概要

`attach_huggingface_oauth` 関数は、FastAPI アプリケーションにログイン、ログアウト、およびコールバックのエンドポイントを追加します。Space で使用する場合、Hugging Face の OAuth システムに接続します。ローカルで使用する場合、モックされたユーザーが注入されます。[Space に Sign-In with HF オプションを追加する方法](https://huggingface.co/docs/hub/en/spaces-oauth)の詳細については、こちらをクリックしてください。

### どのように使用しますか？

```python
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}!"}
```

> [!TIP]
> [OAuthの動作を実演する実践的な例](https://huggingface.co/spaces/Wauplin/fastapi-oauth/blob/main/app.py)もご興味があるかもしれません。より包括的な実装については、HF OAuthをフルスケールのアプリケーションで実装している[medoidai/GiveBackGPT](https://huggingface.co/spaces/medoidai/GiveBackGPT) Spaceをご覧ください。

### attach_huggingface_oauth[[huggingface_hub.attach_huggingface_oauth]]

#### huggingface_hub.attach_huggingface_oauth[[huggingface_hub.attach_huggingface_oauth]]

```python
huggingface_hub.attach_huggingface_oauth(app: fastapi.FastAPI, route_prefix: str = '/')
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_oauth.py#L125)

FastAPI アプリケーションに OAuth エンドポイントを追加して、Hugging Face による OAuth ログインを有効にします。

使用方法:
- このメソッドを FastAPI アプリに呼び出して、OAuth エンドポイントを追加します。
- ルートハンドラー内で`parse_huggingface_oauth(request)`を呼び出し、OAuth情報を取得します。
- ユーザーがログインしている場合、ユーザー情報を含む[OAuthInfo](/docs/huggingface_hub/v2.5.0/ja/package_reference/oauth#huggingface_hub.OAuthInfo)オブジェクトが返されます。ログインしていない場合は、`None`が返されます。
- アプリでは、ユーザーがログインおよびログアウトできるように、`/oauth/huggingface/login` と `/oauth/huggingface/logout` へのリンクを追加してください。

例:
```py
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]]

#### huggingface_hub.parse_huggingface_oauth[[huggingface_hub.parse_huggingface_oauth]]

```python
huggingface_hub.parse_huggingface_oauth(request: fastapi.Request)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_oauth.py#L197)

ログイン済みユーザーの情報を[OAuthInfo](/docs/huggingface_hub/v2.5.0/ja/package_reference/oauth#huggingface_hub.OAuthInfo)オブジェクトとして返します。

柔軟性と将来の拡張性を考慮し、このメソッドはパース処理に対して非常に寛容であり、エラーを発生させません。欠落しているフィールドは警告なしで`None`に設定されます。

ユーザーがログインしていない場合（セッションクッキーに情報がない場合）、`None`を返します。

このメソッドの使用方法の例については、[attach_huggingface_oauth()](/docs/huggingface_hub/v2.5.0/ja/package_reference/oauth#huggingface_hub.attach_huggingface_oauth)を参照してください。

### OAuthOrgInfo[[huggingface_hub.OAuthOrgInfo]]

#### huggingface_hub.OAuthOrgInfo[[huggingface_hub.OAuthOrgInfo]]

```python
huggingface_hub.OAuthOrgInfo(sub: str, name: str, preferred_username: str, picture: str, plan: str | None = None, can_pay: bool | None = None, role_in_org: str | None = None, security_restrictions: list[typing.Literal['ip', 'token-policy', 'mfa', 'sso']] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_oauth.py#L24)

**パラメータ:**

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]`, *optional*) : ユーザーの組織内での役割。Hugging Face のフィールド。

security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *任意*) : この組織において、ユーザーが未完了のセキュリティ制限の配列です。可能な値: "ip", "token-policy", "mfa", "sso"。Hugging Face のフィールドです。

OAuthでログインしたユーザーに関連付けられた組織に関する情報。

### OAuthUserInfo[[huggingface_hub.OAuthUserInfo]]

#### huggingface_hub.OAuthUserInfo[[huggingface_hub.OAuthUserInfo]]

```python
huggingface_hub.OAuthUserInfo(sub: str, name: str, preferred_username: str, email_verified: bool | None, email: str | None, picture: str, profile: str, website: str | None, is_pro: bool, can_pay: bool | None, orgs: list[huggingface_hub._oauth.OAuthOrgInfo] | None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_oauth.py#L58)

**パラメータ:**

sub (`str`) : ユーザーの一意な識別子。名前が変更された場合でも一意性を保ちます。OpenID Connect のフィールドです。

name (`str`) : ユーザーの氏名。OpenID Connect フィールド。

preferred_username (`str`) : ユーザーのユーザー名。OpenID Connect フィールド。

email_verified (`Optional[bool]`, *任意*) : ユーザーのメールアドレスが認証済みかどうかを示します。OpenID Connect フィールドです。

email (`Optional[str]`, *optional*) : ユーザーのメールアドレス。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]]

#### huggingface_hub.OAuthInfo[[huggingface_hub.OAuthInfo]]

```python
huggingface_hub.OAuthInfo(access_token: str, access_token_expires_at: datetime, user_info: OAuthUserInfo, state: str | None, scope: str)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_oauth.py#L101)

**パラメータ:**

access_token (`str`) : アクセストークン。

access_token_expires_at (`datetime.datetime`) : アクセストークンの有効期限。

user_info ([OAuthUserInfo](/docs/huggingface_hub/v2.5.0/ja/package_reference/oauth#huggingface_hub.OAuthUserInfo)) : ユーザー情報。

state (`str`, *任意*) : 元のOAuthプロバイダーへのリクエストで、OAuthプロバイダーに渡される状態。

scope (`str`) : 付与されたスコープ。

OAuthログインに関する情報。

