跳到内容

Strapi + Provider authjs


社区authjsstrapi
justserdar

本节提供了一个示例,说明如何配置 NuxtAuthHandler 以使用 Strapi JWT 通过 CredentialsProvider 提供程序进行身份验证。

您必须配置以下位置才能使 nuxt-auth 与 Strapi 一起工作

对于生产部署,您至少需要设置

  1. 创建包含以下行的 .env 文件
// Strapi v4 url, out of the box
AUTH_ORIGIN=http://localhost:3000
NUXT_SECRET=a-not-so-good-secret
STRAPI_BASE_URL=http://localhost:1337/api
  1. 在您的 nuxt.config.ts 中设置以下选项
ts
export default defineNuxtConfig({
  runtimeConfig: {
    // The private keys which are only available server-side
    NUXT_SECRET: process.env.NUXT_SECRET,
    // Default http://localhost:1337/api
    STRAPI_BASE_URL: process.env.STRAPI_BASE_URL,
  },
})
  1. 创建 catch-all NuxtAuthHandler 并添加此自定义 Strapi 凭据提供程序
ts
// file: ~/server/api/auth/[...].ts
import CredentialsProvider from 'next-auth/providers/credentials'
import { NuxtAuthHandler } from '#auth'
const config = useRuntimeConfig()

export default NuxtAuthHandler({
  secret: config.NUXT_SECRET,
  providers: [
    // @ts-expect-error You need to use .default here for it to work during SSR. May be fixed via Vite at some point
    CredentialsProvider.default({
      name: 'Credentials',
      credentials: {}, // Object is required but can be left empty.
      async authorize(credentials: any) {
        const response = await $fetch(
          `${config.STRAPI_BASE_URL}/auth/local/`,
          {
            method: 'POST',
            body: JSON.stringify({
              identifier: credentials.username,
              password: credentials.password,
            }),
          }
        )

        if (response.user) {
          const u = {
            id: response.id,
            name: response.user.username,
            email: response.user.email,
          }
          return u
        }
        else {
          return null
        }
      },
    }),
  ]
})

了解更多

查看这篇博客文章以获取更多注释和解释: https://darweb.nl/foundry/article/nuxt3-sidebase-strapi-user-auth

在 MIT 许可证下发布。