email-and-password-best-practices について
Better Authでメールアドレスとパスワードによる認証を実装する開発者向けのスキルです。メール確認、パスワードリセット、トークン管理、セッション失効、検証、ハッシュ設定を説明します。
主な機能
- 01メール確認の設定
- 02パスワードリセットフローの設定
- 03リセットトークンの有効期限と一回限りの使用
- 04パスワードリセット後のセッション失効
- 05パスワード長とハッシュの設定
活用シーン
- 01サインアップへのメール確認の追加
- 02パスワードリセットフローの構築
- 03認証情報変更後のセッション失効
- 04カスタムパスワードハッシュ関数の選択
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ better-auth/ skills --skill email-and-password-best-practicesインストール後、Claude Code で/email-and-password-best-practicesを入力して読み込まれたか確認します。
詳細
クイックスタート
- メールアドレス/パスワード認証を有効にします:
emailAndPassword: { enabled: true } emailVerification.sendVerificationEmailを設定します- パスワードリセットフロー用に
sendResetPasswordを追加します npx auth@latest migrateを実行します- サインアップを試し、確認メールが送信されることを確認します
メールアドレス確認の設定
emailVerification.sendVerificationEmail を設定して、ユーザーのメールアドレスを確認します。
import { betterAuth } from "better-auth";
import { sendEmail } from "./email"; // your email sending function
export const auth = betterAuth({
emailVerification: {
sendVerificationEmail: async ({ user, url, token }, request) => {
await sendEmail({
to: user.email,
subject: "Verify your email address",
text: `Click the link to verify your email: ${url}`,
});
},
},
});
注:url パラメーターには確認リンク全体が含まれます。カスタムの確認 URL を作成する必要がある場合は、token を利用できます。
メールアドレス確認の必須化
セキュリティを強化するには、emailAndPassword.requireEmailVerification を有効にして、ユーザーがメールアドレスを確認するまでサインインをブロックします。有効にすると、未確認のユーザーには、サインインを試みるたびに新しい確認メールが送信されます。
export const auth = betterAuth({
emailAndPassword: {
requireEmailVerification: true,
},
});
注:この設定には sendVerificationEmail の設定が必要で、メールアドレス/パスワードによるサインインにのみ適用されます。
クライアント側の検証
ユーザーにすぐにフィードバックを提供し、サーバーの負荷を軽減するために、クライアント側の検証を実装します。
コールバック URL
サインアップおよびサインインのリクエストでは、コールバック URL に常に絶対 URL(オリジンを含む)を使用してください。これにより、Better Auth がオリジンを推測する必要がなくなります。バックエンドとフロントエンドが異なるドメインにある場合に発生し得る問題を防げます。
const { data, error } = await authClient.signUp.email({
callbackURL: "https://example.com/callback", // absolute URL with origin
});
パスワードリセットフロー
パスワードリセットを有効にするには、メールアドレス/パスワードの設定に sendResetPassword を指定します。
import { betterAuth } from "better-auth";
import { sendEmail } from "./email"; // your email sending function
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
// Custom email sending function to send reset-password email
sendResetPassword: async ({ user, url, token }, request) => {
void sendEmail({
to: user.email,
subject: "Reset your password",
text: `Click the link to reset your password: ${url}`,
});
},
// Optional event hook
onPasswordReset: async ({ user }, request) => {
// your logic here
console.log(`Password for user ${user.email} has been reset.`);
},
},
});
セキュリティ上の考慮事項
組み込みの保護機能:バックグラウンドでのメール送信(タイミング攻撃の防止)、無効なリクエストに対するダミー操作、ユーザーの存在にかかわらず同じ応答メッセージを返します。
サーバーレスプラットフォームでは、バックグラウンドタスクハンドラーを設定します。
export const auth = betterAuth({
advanced: {
backgroundTasks: {
handler: (promise) => {
// Use platform-specific methods like waitUntil
waitUntil(promise);
},
},
},
});
トークンのセキュリティ
トークンの有効期限は、デフォルトで 1 時間です。resetPasswordTokenExpiresIn(秒単位)で設定できます。
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
resetPasswordTokenExpiresIn: 60 * 30, // 30 minutes
},
});
トークンは 1 回のみ使用でき、リセットの成功直後に削除されます。
セッションの失効
パスワードリセット時に既存のセッションをすべて無効にするには、revokeSessionsOnPasswordReset を有効にします。
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
revokeSessionsOnPasswordReset: true,
},
});
パスワード要件
パスワードの長さ制限(設定可能):
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
minPasswordLength: 12,
maxPasswordLength: 256,
},
});
パスワードリセットの送信
requestPasswordReset を呼び出してリセットリンクを送信します。設定内の sendResetPassword 関数が呼び出されます。
const data = await auth.api.requestPasswordReset({
body: {
email: "[email protected]", // required
redirectTo: "https://example.com/reset-password",
},
});
または、authClient を使用します。
const { data, error } = await authClient.requestPasswordReset({
email: "[email protected]", // required
redirectTo: "https://example.com/reset-password",
});
注:email は必須ですが、ユーザー体験をよりスムーズにするため、redirectTo も設定することをおすすめします。
パスワードのハッシュ化
デフォルト:scrypt(Node.js ネイティブで、外部依存関係はありません)。
カスタムハッシュ化アルゴリズム
Argon2id または別のアルゴリズムを使用するには、カスタムの hash 関数と verify 関数を指定します。
import { betterAuth } from "better-auth";
import { hash, verify, type Options } from "@node-rs/argon2";
const argon2Options: Options = {
memoryCost: 65536, // 64 MiB
timeCost: 3, // 3 iterations
parallelism: 4, // 4 parallel lanes
outputLen: 32, // 32 byte output
algorithm: 2, // Argon2id variant
};
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
password: {
hash: (password) => hash(password, argon2Options),
verify: ({ password, hash: storedHash }) =>
verify(storedHash, password, argon2Options),
},
},
});
注:既存のシステムでハッシュ化アルゴリズムを切り替えると、旧アルゴリズムでハッシュ化されたパスワードを持つユーザーはサインインできなくなります。必要に応じて、移行戦略を計画してください。