Skip to content

验证

身份验证和授权是管理对你的网站或应用的访问的两个安全过程。身份验证验证访问者的身份,而授权授予对受保护区域和资源的访问权限。

¥Authentication and authorization are two security processes that manage access to your website or app. Authentication verifies a visitor’s identity, while authorization grants access to protected areas and resources.

身份验证允许你为登录的个人自定义站点区域,并为个人或私有信息提供最大程度的保护。身份验证库(例如 Auth.js店员)为多种身份验证方法(例如电子邮件登录和 OAuth 提供程序)提供实用程序。

¥Authentication allows you to customize areas of your site for logged-in individuals and provides the greatest protection for personal or private information. Authentication libraries (e.g. Auth.js, Clerk) provide utilities for multiple authentication methods such as email sign-in and OAuth providers.

See how to add authentication with Supabase or add authentication with Firebase in our dedicated guides for these backend services.

Auth.js 是一种与框架无关的身份验证解决方案。Astro 提供社区框架适配器 auth-astro

¥Auth.js is a framework agnostic solution for authentication. A community framework adapter auth-astro is available for Astro.

¥Installation

使用你首选的包管理器的 astro add 命令来添加 auth-astro 集成。

¥Use the astro add command for your preferred package manager to add the auth-astro integration.

终端窗口
npx astro add auth-astro

¥Manual installation

要手动安装 auth-astro,请为你的包管理器安装所需的包:

¥To install auth-astro manually, install the required package for your package manager:

终端窗口
npm install auth-astro @auth/core@^0.18.6

然后,使用 integrations 属性将集成应用于你的 astro.config.* 文件:

¥Then, apply the integration to your astro.config.* file using the integrations property:

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

¥Configuration

在项目的根目录中创建一个 auth.config.ts 文件。添加你希望支持的任何身份验证 providers 或方法,以及它们所需的任何环境变量。

¥Create an auth.config.ts file in your project’s root directory. Add any auth providers or methods you wish to support, along with any environment variables they require.

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 个字符的私有字符串。

¥Create a .env file in the root of your project if it does not already exist. Add the following two environment variables. AUTH_SECRET should be a private string with a minimum of 32 characters.

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

¥Usage

你可以使用脚本标记或客户端框架组件中的 auth-astro/client 模块添加登录和退出按钮。

¥You can add sign-in and sign-out buttons using the auth-astro/client module in a script tag or client-side framework component.

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
---
<Layout>
<button id="login">Login</button>
<button id="logout">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 方法获取用户的会话。

¥You can fetch the user’s session using the getSession method.

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>Welcome {session.user?.name}</p>
) : (
<p>Not logged in</p>
)
}
</Layout>

¥Next Steps

¥Better Auth

Better Auth 是一个与框架无关的 TypeScript 身份验证(和授权)框架。它提供了一套全面的开箱即用的功能,并包含一个插件生态系统,可简化添加高级功能。

¥Better Auth is a framework-agnostic authentication (and authorization) framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities.

它开箱即用地支持 Astro,你可以使用它为你的 astro 项目添加身份验证。

¥It supports Astro out of the box, and you can use it to add authentication to your astro project.

¥Installation

终端窗口
npm install better-auth

有关详细的设置说明,请查看 Better Auth 安装指南

¥For detailed setup instructions, check out the Better Auth Installation Guide.

¥Configuration

配置你的数据库表以存储用户数据和你首选的身份验证方法,如 Better Auth 安装指南 中所述。然后,你需要在你的 Astro 项目中安装 Better Auth 处理程序。

¥Configure your database table to store user data and your preferred authentication methods as described in the Better Auth Installation Guide. Then, you’ll need to mount the Better Auth handler in your Astro project.

page/api/auth/[...all].ts
import { auth } from "../../../lib/auth"; // import your Better Auth instance
import type { APIRoute } from "astro";
export const ALL: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};

关注 Better Auth Astro 指南 了解更多信息。

¥Follow the Better Auth Astro Guide to learn more.

¥Usage

Better Auth 为各种框架提供了 createAuthClient 助手,包括 Vanilla JS、React、Vue、Svelte 和 Solid。

¥Better Auth offers a createAuthClient helper for various frameworks, including Vanilla JS, React, Vue, Svelte, and Solid.

例如,要为 React 创建客户端,请从 'better-auth/react' 导入助手:

¥For example, to create a client for React, import the helper from '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() 功能登录或注销的能力。

¥Once your client is set up, you can use it to authenticate users in your Astro components or any framework-specific files. The following example adds the ability to log in or log out with your configured signIn() and signOut() functions.

src/pages/index.astro
---
import Layout from 'src/layouts/Base.astro';
---
<Layout>
<button id="login">Login</button>
<button id="logout">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 对象在服务器端代码中获取用户的会话数据。以下示例通过显示经过身份验证的用户的名称来个性化页面内容:

¥You can then use the auth object to get the user’s session data in your server-side code. The following example personalizes page content by displaying an authenticated user’s name:

src/pages/index.astro
---
import { auth } from "../../../lib/auth"; // import your Better Auth instance
const session = await auth.api.getSession({
headers: Astro.request.headers,
});
---
<p>{session.user?.name}</p>

你还可以使用 auth 对象通过中间件保护你的路由。以下示例检查尝试访问已登录仪表板路由的用户是否经过身份验证,如果没有,则将其重定向到主页。

¥You can also use the auth object to protect your routes using middleware. The following example checks whether a user trying to access a logged-in dashboard route is authenticated, and redirects them to the home page if not.

src/middleware.ts
import { auth } from "../../../auth"; // import your Better Auth instance
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();
});

¥Next Steps

¥Clerk

Clerk 是一套完整的可嵌入 UI、灵活的 API 和管理仪表板,用于对你的用户进行身份验证和管理。Astro 官方 Clerk SDK 可用。

¥Clerk is a complete suite of embeddable UIs, flexible APIs, and admin dashboards to authenticate and manage your users. An official Clerk SDK for Astro is available.

¥Installation

使用你选择的包管理器安装 @clerk/astro

¥Install @clerk/astro using the package manager of your choice.

终端窗口
npm install @clerk/astro

¥Configuration

按照 Clerk 自己的 Astro 快速入门指南 在你的 Astro 项目中设置 Clerk 集成和中间件。

¥Follow Clerk’s own Astro Quickstart guide to set up Clerk integration and middleware in your Astro project.

¥Usage

Clerk 提供的组件允许你根据用户的身份验证状态控制页面的可见性。向已注销的用户显示登录按钮,而不是向已登录的用户显示内容:

¥Clerk provides components that allow you to control the visibility of pages based on your user’s authentication state. Show logged out users a sign in button instead of the content available to users who are logged in:

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 还允许你使用中间件保护服务器上的路由。指定哪些路由受到保护,并提示​​未经身份验证的用户登录:

¥Clerk also allows you to protect routes on the server using middleware. Specify which routes are protected, and prompt unauthenticated users to sign in:

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();
}
});

¥Next Steps

Lucia 是一种资源,用于在包括 Astro 在内的许多框架中实现基于会话的身份验证。

¥Lucia is a resource for implementing session-based authentication in a number of frameworks, including Astro.

¥Guides

  1. Create a basic sessions API with your chosen database.
  2. Add session cookies using endpoints and middleware.
  3. Implement GitHub OAuth using the APIs you implemented.

¥Examples

¥Community Resources

Astro 中文网 - 粤ICP备13048890号