主题
更好的身份验证
¥Better Auth
Better Auth 是一个与框架无关的 TypeScript 身份验证(和授权)框架。
¥Better Auth is 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.
我们建议你在浏览此页面之前先了解一下 更好的身份验证基本设置。
¥We recommend going through the Better Auth basic setup before going through this page.
我们的基本设置如下所示:
¥Our basic setup will look like this:
ts
import { betterAuth } from 'better-auth'
import { Pool } from 'pg'
export const auth = betterAuth({
database: new Pool()
})
处理程序
¥Handler
设置 Better Auth 实例后,我们可以通过 mount 挂载到 Elysia。
¥After setting up Better Auth instance, we can mount to Elysia via mount.
我们需要将处理程序挂载到 Elysia 端点。
¥We need to mount the handler to Elysia endpoint.
ts
import { Elysia } from 'elysia'
import { auth } from './auth'
const app = new Elysia()
.mount(auth.handler)
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
然后我们就可以使用 http://localhost:3000/api/auth
访问 Better Auth 了。
¥Then we can access Better Auth with http://localhost:3000/api/auth
.
自定义端点
¥Custom endpoint
我们建议在使用 mount 时设置前缀路径。
¥We recommend setting a prefix path when using mount.
ts
import { Elysia } from 'elysia'
const app = new Elysia()
.mount('/auth', auth.handler)
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
然后我们就可以使用 http://localhost:3000/auth/api/auth
访问 Better Auth 了。
¥Then we can access Better Auth with http://localhost:3000/auth/api/auth
.
但 URL 看起来是多余的,我们可以在 Better Auth 实例中将 /api/auth
前缀自定义为其他内容。
¥But the URL looks redundant, we can customize the /api/auth
prefix to something else in Better Auth instance.
ts
import { betterAuth } from 'better-auth'
import { openAPI } from 'better-auth/plugins'
import { passkey } from 'better-auth/plugins/passkey'
import { Pool } from 'pg'
export const auth = betterAuth({
basePath: '/api'
})
然后我们就可以使用 http://localhost:3000/auth/api
访问 Better Auth 了。
¥Then we can access Better Auth with http://localhost:3000/auth/api
.
遗憾的是,我们无法将 Better Auth 实例的 basePath
设置为空或 /
。
¥Unfortunately, we can't set basePath
of a Better Auth instance to be empty or /
.
OpenAPI
Better Auth 支持 openapi
和 better-auth/plugins
。
¥Better Auth support openapi
with better-auth/plugins
.
但是,如果我们使用 @elysiajs/openapi,你可能需要从 Better Auth 实例中提取文档。
¥However if we are using @elysiajs/openapi, you might want to extract the documentation from Better Auth instance.
我们可以使用以下代码执行此操作:
¥We may do that with the following code:
ts
import { openAPI } from 'better-auth/plugins'
let _schema: ReturnType<typeof auth.api.generateOpenAPISchema>
const getSchema = async () => (_schema ??= auth.api.generateOpenAPISchema())
export const OpenAPI = {
getPaths: (prefix = '/auth/api') =>
getSchema().then(({ paths }) => {
const reference: typeof paths = Object.create(null)
for (const path of Object.keys(paths)) {
const key = prefix + path
reference[key] = paths[path]
for (const method of Object.keys(paths[path])) {
const operation = (reference[key] as any)[method]
operation.tags = ['Better Auth']
}
}
return reference
}) as Promise<any>,
components: getSchema().then(({ components }) => components) as Promise<any>
} as const
然后在使用 @elysiajs/swagger
的 Elysia 实例中。
¥Then in our Elysia instance that use @elysiajs/swagger
.
ts
import { Elysia } from 'elysia'
import { openapi } from '@elysiajs/openapi'
import { OpenAPI } from './auth'
const app = new Elysia().use(
openapi({
documentation: {
components: await OpenAPI.components,
paths: await OpenAPI.getPaths()
}
})
)
CORS
要配置 cors,你可以使用 @elysiajs/cors
中的 cors
插件。
¥To configure cors, you can use the cors
plugin from @elysiajs/cors
.
ts
import { Elysia } from 'elysia'
import { cors } from '@elysiajs/cors'
import { auth } from './auth'
const app = new Elysia()
.use(
cors({
origin: 'http://localhost:3001',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
})
)
.mount(auth.handler)
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
宏
¥Macro
你可以将 macro 和 resolve 结合使用,在传递到视图之前提供会话和用户信息。
¥You can use macro with resolve to provide session and user information before pass to view.
ts
import { Elysia } from 'elysia'
import { auth } from './auth'
// user middleware (compute user and session and pass to routes)
const betterAuth = new Elysia({ name: 'better-auth' })
.mount(auth.handler)
.macro({
auth: {
async resolve({ status, request: { headers } }) {
const session = await auth.api.getSession({
headers
})
if (!session) return status(401)
return {
user: session.user,
session: session.session
}
}
}
})
const app = new Elysia()
.use(betterAuth)
.get('/user', ({ user }) => user, {
auth: true
})
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
这将允许你在所有路由中访问 user
和 session
对象。
¥This will allow you to access the user
and session
object in all of your routes.