Open1

openid connectのサンプル

メモdevメモdev

openid connectの検証。なお以下はcopilotの返答です。

FastAPIでOpenID Connect(OIDC)を使ってGoogleログイン、もちろんできます!しかもFastAPIは非同期処理に強く、Authlibなどのライブラリと組み合わせると、かなりスマートに実装できますよ。以下はその流れです👇


🚀 FastAPI × Google OIDC ログインの実装ステップ

① 必要なライブラリをインストール

pip install fastapi uvicorn authlib python-dotenv

.env ファイルを作成(Google Cloud Consoleで取得した情報)

GOOGLE_CLIENT_ID=あなたのクライアントID
GOOGLE_CLIENT_SECRET=あなたのクライアントシークレット
GOOGLE_REDIRECT_URI=http://localhost:8000/auth

③ FastAPIアプリのコード例(Authlib使用)

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from authlib.integrations.starlette_client import OAuth
from starlette.config import Config
from starlette.responses import RedirectResponse
import os

# 環境変数の読み込み
config = Config('.env')
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.urandom(24))

# OAuth設定
oauth = OAuth(config)
oauth.register(
    name='google',
    server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
    client_kwargs={'scope': 'openid email profile'}
)

@app.get('/')
async def homepage():
    return {'message': 'Googleログインは /login へ'}

@app.get('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri)

@app.get('/auth')
async def auth(request: Request):
    token = await oauth.google.authorize_access_token(request)
    user = token['userinfo']
    return {'user': user}

④ 実行して確認

uvicorn main:app --reload

http://localhost:8000/login にアクセス
→ Googleログイン後、ユーザー情報が表示されれば成功!


🧠 補足ポイント

  • server_metadata_url を使うことで、GoogleのOIDC設定を自動取得できます
  • userinfoemail, name, picture などが含まれます
  • セッション管理は SessionMiddleware で簡単に扱えます

📚 参考になる実装記事


FastAPIを練習中なら、OIDCはかなり良い題材です!セキュリティ、非同期処理、セッション管理など、実践的な技術が詰まってます。次は「ログイン後のユーザー管理」や「JWTの検証」などもやってみませんか?