serverpod-auth について
Serverpod Authenticationは、ServerpodのサーバーとFlutterアプリ向けの認証機能です。サインインUI、ユーザープロフィール、認証状態、エンドポイントのアクセス制御を備えています。
主な機能
- 01ログインまたは特定スコープを要求
- 02認証済みユーザーIDとプロフィールの取得
- 03SignInWidgetによるサインイン
- 04認証状態の変更を監視
- 05単一または全デバイスからサインアウト
活用シーン
- 01ログインユーザーにエンドポイントを限定
- 02スコープでメソッドを保護
- 03Flutterアプリにサインイン画面を追加
- 04プロフィールの取得やセッション終了
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ serverpod/ serverpod --skill serverpod-authインストール後、Claude Code で/serverpod-authを入力して読み込まれたか確認します。
同梱ファイルreferences/setup.mdreferences/user-management.md
詳細
Serverpod 認証
Serverpod には認証機能が組み込まれています。serverpod create で作成したプロジェクトでは、デフォルトで有効になっており(--no-auth を指定した場合、またはプロジェクトにデータベースがない場合を除く)、メールアドレス認証があらかじめ設定され、lib/server.dart と Flutter アプリにすでに組み込まれています。
サーバーアプリケーションのコードでは、package:serverpod_auth_idp_server/core.dart と package:serverpod_auth_idp_server/providers/<provider>.dart をインポートしてください。package:serverpod_auth_idp_server/serverpod_auth_idp_server.dart はインポートしないでください。このライブラリはコードジェネレーター用です。
サーバー側
ユーザーにサインイン、または特定のスコープを要求する
class MyEndpoint extends Endpoint {
// Require the user to be signed in to access methods in this endpoint.
@override
bool get requireLogin => true;
// Require the user to have the admin scope.
@override
Set<Scope> get requiredScopes => {Scope.admin};
// This method can only be accessed if the user is admin.
Future<void> myMethod(Session session) async {
...
}
...
}
ユーザー ID と情報
import 'package:serverpod_auth_idp_server/core.dart';
// Get authenticated user's ID.
final userIdUuidValue = session.authenticated?.authUserId;
// Get the user profile (full name, email, etc)
var userProfile = await session.authenticated?.userProfile(session);
// Find a user profile by email.
final profiles = await AuthServices.instance.userProfiles.admin
.listUserProfiles(
session,
email: email.toLowerCase(),
limit: 1,
);
final userProfile = profiles.firstOrNull;
// Get authentication info for user id (for editing scopes, etc).
final authUsers = AuthServices.instance.authUsers;
final authUser = await authUsers.get(
session,
authUserId: userProfile.authUserId,
);
Flutter アプリ
SignInWidget を使用してユーザーをサインインさせます。このウィジェットは独自の Material サーフェスを提供するため、Material 以外のデザインシステムと組み合わせても正しく描画されます。
SignInWidget(
client: client,
onAuthenticated: () => _showSnackBar(message: 'User authenticated.'),
onError: (error) => _showSnackBar(message: 'Authentication failed: $error'),
)
- サインイン状態:
client.auth.isAuthenticated。変更時に再ビルドするには、client.auth.authInfoListenable(ValueListenable<AuthSuccess?>なので、ValueListenableBuilderも使用できます)をリッスンし、disposeでリスナーを削除します。 - サインアウト:
client.auth.signOutAllDevices()またはclient.auth.signOutDevice()。 - ユーザープロフィール(メールアドレス、氏名など):
await client.modules.serverpod_auth_core.userProfileInfo.get()。
詳細
references/setup.md— 認証なしで作成したプロジェクトへの認証パッケージの追加、server.dartでのサービスの初期化、Flutter クライアントの接続、ソーシャルサインインの設定、レガシーなserverpod_authモジュールからの移行について説明します。references/user-management.md— ユーザーへの独自データの紐付け、スコープの編集、クライアントによるプロフィール編集について説明します。