コンテンツにスキップ

認証

認証と認可はウェブサイトやアプリへのアクセスを管理する2つのセキュリティプロセスです。認証は訪問者のアイデンティティを検証し、認可は保護領域やリソースへのアクセスを許可します。

認証を導入すると、ログイン済みユーザー向けにサイトをカスタマイズでき、個人情報を安全に保護できます。認証ライブラリ(例: Auth.jsClerk)は、メールサインインやOAuthなど複数の認証方法を提供します。

バックエンドサービスごとの専用ガイド: Supabaseで認証を追加 (EN)Firebaseで認証を追加 (EN)

Auth.jsはフレームワークに依存しない認証ライブラリです。Astro向けにコミュニティ製アダプタauth-astroが提供されています。

任意のパッケージマネージャでastro addコマンドを実行し、auth-astroインテグレーションを追加します。

ターミナルウィンドウ
npx astro add auth-astro

auth-astroを手動で導入する場合は次のパッケージをインストールします。

ターミナルウィンドウ
npm install auth-astro @auth/core@^0.18.6

続いて astro.config.*ファイルのintegrationsプロパティに追加します。

astro.config.mjs
import { defineConfig } from 'astro/config';
import auth from 'auth-astro';
export default defineConfig({
// ...
integrations: [auth()],
});

プロジェクトのルートにauth.config.tsファイルを作成し、利用したい認証プロバイダやメソッドを追加します。

auth.config.ts
import GitHub from '@auth/core/providers/github';
import { defineConfig } from 'auth-astro';
export default defineConfig({
providers: [
GitHub({
clientId: import.meta.env.GITHUB_CLIENT_ID,
clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
}),
],
});

.envファイルが未作成ならルートに置き、次の環境変数を設定します。AUTH_SECRETは32文字以上のランダム文字列にしてください。

.env
AUTH_TRUST_HOST=true
AUTH_SECRET=<my-auth-secret>

サインイン/サインアウトボタンをauth-astro/clientモジュールで追加できます。

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
---
<Layout>
<button id="login">ログイン</button>
<button id="logout">ログアウト</button>
<script>
const { signIn, signOut } = await import('auth-astro/client')
document.querySelector('#login').onclick = () => signIn('github')
document.querySelector('#logout').onclick = () => signOut()
</script>
</Layout>

ユーザーセッションはgetSessionで取得できます。

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
import { getSession } from 'auth-astro/server';
const session = await getSession(Astro.request);
---
<Layout>
{
session ? (
<p>{session.user?.name}さん、ようこそ</p>
) : (
<p>未ログイン</p>
)
}
</Layout>

Better AuthはTypeScript向けのフレームワークに依存しない認証・認可フレームワークです。豊富な標準機能とプラグインエコシステムがあり、高度な機能も簡単に追加できます。

Astroを公式サポートしているため、Astroプロジェクトに手軽に認証を導入できます。

ターミナルウィンドウ
npm install better-auth

詳細なセットアップはBetter Authインストールガイドを参照してください。

Better Authインストールガイドに従って、ユーザーデータと利用したい認証方式を保存できるようデータベーステーブルを設定してください。その後、Better AuthのハンドラーをAstroプロジェクトにマウントします。

src/pages/api/auth/[...all].ts
import { auth } from '../../../lib/auth'; // Better Auth インスタンス
import type { APIRoute } from 'astro';
export const ALL: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};

詳しくはBetter Auth Astroガイドを参照してください。

Better Authは、Vanilla JS、React、Vue、Svelte、Solidなど複数のフレームワーク向けにcreateAuthClientヘルパーを提供しています。

たとえば、React用のクライアントを作成するには、'better-auth/react'からヘルパーをインポートします。

src/lib/auth-client.ts
import { createAuthClient } from 'better-auth/react';
export const authClient = createAuthClient();
export const { signIn, signOut } = authClient;

クライアントのセットアップが完了したら、Astroコンポーネントや任意のフレームワーク専用ファイル内でユーザー認証に利用できます。次の例では、設定済みのsignIn()signOut()関数でログイン/ログアウト機能を追加しています。

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
---
<Layout>
<button id="login">ログイン</button>
<button id="logout">ログアウト</button>
<script>
const { signIn, signOut } = await import("./lib/auth-client")
document.querySelector("#login").onclick = () => signIn.social({
provider: "github",
callbackURL: "/dashboard",
})
document.querySelector("#logout").onclick = () => signOut()
</script>
</Layout>

続いて、サーバー側コードでauthオブジェクトを用いてユーザーのセッションデータを取得できます。次の例では、認証済みユーザーの名前を表示してページ内容をパーソナライズしています。

src/pages/index.astro
---
import { auth } from "../../../lib/auth"; // Better Authインスタンスをインポート
const session = await auth.api.getSession({
headers: Astro.request.headers,
});
---
<p>{session.user?.name}</p>

さらに、authオブジェクトを使ってミドルウェアでルートを保護することもできます。次の例では、ログイン後のダッシュボード (/dashboard) にアクセスしようとするユーザーが認証済みかを確認し、未認証の場合はホームページへリダイレクトします。

src/middleware.ts
import { auth } from "../../../auth"; // Better Authインスタンスをインポート
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware(async (context, next) => {
const isAuthed = await auth.api
.getSession({
headers: context.request.headers,
})
if (context.url.pathname === "/dashboard" && !isAuthed) {
return context.redirect("/");
}
return next();
});

ClerkはUIコンポーネント、API、管理ダッシュボードを備えたユーザー管理サービスです。公式Clerk SDK for Astro が提供されています。

任意のパッケージマネージャで @clerk/astro を追加します。

ターミナルウィンドウ
npm install @clerk/astro

ClerkのAstroクイックスタートガイドに従い、AstroプロジェクトにClerkインテグレーションとミドルウェアを設定します。

Clerkは、ユーザーの認証状態に応じてページの表示可否を制御できるコンポーネントを提供します。未ログインの訪問者には、ログインユーザー向けコンテンツの代わりにサインインボタンを表示できます。

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
import { SignedIn, SignedOut, UserButton, SignInButton } from '@clerk/astro/components';
---
<Layout>
<SignedIn>
<UserButton />
</SignedIn>
<SignedOut>
<SignInButton />
</SignedOut>
</Layout>

またClerkでは、ミドルウェアを使ってサーバー側でルートを保護できます。保護対象のルートを指定し、未認証ユーザーにはサインインを促します。

src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/forum(.*)',
]);
export const onRequest = clerkMiddleware((auth, context) => {
if (!auth().userId && isProtectedRoute(context.request)) {
return auth().redirectToSignIn();
}
});

Luciaはセッションベース認証を複数フレームワークで実装できるライブラリーで、Astroもサポートしています。

  1. 任意のデータベースで基本セッションAPIを実装します。
  2. エンドポイントとミドルウェアでセッションクッキーを追加します。
  3. 実装したAPIを使ってGitHub OAuthを組み込みます。
貢献する コミュニティ スポンサー