乐闻世界logo
搜索文章和话题

NextAuth 如何实现自定义 Provider ?

4 个月前提问
3 个月前修改
浏览次数99

1个答案

1

NextAuth.js 是一个用于 Next.js 应用的完整的登录、身份验证和会话管理解决方案。如果你想使用 NextAuth.js 添加一个自定义的认证提供者,可以按照以下步骤进行:

步骤 1: 安装 NextAuth.js

如果你还没有安装 NextAuth.js,可以通过 npm 或 yarn 来安装它:

bash
npm install next-auth

或者

bash
yarn add next-auth

步骤 2: 创建 NextAuth.js 配置

在你的 Next.js 应用中,创建一个文件,通常是 [...nextauth].js (通常放在 pages/api/auth 目录下),然后配置 NextAuth.js。在配置中,你可以添加一个 providers 数组,并在其中配置你的自定义提供者。

javascript
import NextAuth from 'next-auth' import Providers from 'next-auth/providers' export default NextAuth({ // Configure one or more authentication providers providers: [ Providers.Credentials({ // The name to display on the sign in form (e.g. 'Sign in with...') name: 'Credentials', // The credentials is used to generate a suitable form on the sign in page. // You can specify whatever fields you are expecting to be submitted. // e.g. domain, username, password, 2FA token, etc. // You can pass any HTML attribute to the input tag through the object. credentials: { username: { label: "Username", type: "text" }, password: { label: "Password", type: "password" } }, authorize: async (credentials) => { // Add logic here to look up the user from the credentials supplied const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' } if (user) { // Any user object returned here will be saved in the JSON Web Token return Promise.resolve(user) } else { return Promise.resolve(null) } } }), // ...add more providers here ], // Add custom pages if needed pages: { signIn: '/auth/signin', signOut: '/auth/signout', error: '/auth/error', // Error code passed in query string as ?error= // ... }, // ...add more options here })

在上面的例子中,我们使用了 Providers.Credentials 创建了一个基于凭据的自定义认证提供者。这个提供者允许你接受任何形式的凭据(例如用户名和密码),并在 authorize 函数中实现验证逻辑。

步骤 3: 实现验证逻辑

authorize 函数中,你需要实现验证用户凭据的逻辑。这通常会涉及检查数据库或调用外部服务以确认用户的身份。

确保在验证成功时返回用户对象,在验证失败时返回 null。返回的用户对象会被用来生成 JSON Web Token,并用于用户的会话。

步骤 4: 使用自定义提供者

一旦你配置了自定义提供者并实现了验证逻辑,你就可以在应用中使用 NextAuth.js 提供的 React 钩子和组件,例如 useSessionsignInsignOut,来管理用户的认证状态。

javascript
import { signIn, signOut, useSession } from 'next-auth/client'; // 某个组件中 function MyComponent() { const [session, loading] = useSession(); const handleSignIn = async () => { // 调用 signIn 函数并传递 'credentials' 以及表单数据 const result = await signIn('credentials', { redirect: false, // 不重定向 username: 'myUsername', password: 'myPassword', }); if (!result.error) { // 登录成功! } }; const handleSignOut = () => { signOut(); }; if (loading) return <div>Loading...</div>; if (!session) return <button onClick={handleSignIn}>Sign In</button>; return ( <div> <p>Welcome, {session.user.name}!</p>
2024年6月29日 12:07 回复

你的答案