要在 Next.js 项目中使用 NextAuth 来通过自定义的 Spring API 库和端点进行身份验证,可以按照以下步骤操作:
配置 NextAuth
在 pages/api/auth/[...nextauth].js
文件中配置 NextAuth:
import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; export default NextAuth({ session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60, // 30 days }, providers: [ CredentialsProvider({ name: "credentials", credentials: { username: { label: "Username", type: "text", placeholder: "[email protected]" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { const res = await fetch("API_LOGIN_URL", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ username: credentials.username, password: credentials.password, }), }); const user = await res.json(); if (res.ok && user) { return user; } else { return null; } }, }), ], callbacks: { async jwt({ token, user }) { if (user) { token.id = user.id; token.accessToken = user.accessToken; } return token; }, async session({ session, token }) { session.user.id = token.id; session.accessToken = token.accessToken; return session; }, }, secret: process.env.SECRET, });
配置登录表单
在你的 AuthForm.js
文件中,使用 next-auth/react
的 signIn
函数来处理表单提交:
import { useRef } from "react"; import { signIn } from "next-auth/react"; import classes from "./AuthForm.module.css"; function AuthForm() { const usernameInputRef = useRef(); const passwordInputRef = useRef(); async function submitHandler(event) { event.preventDefault(); const enteredUsername = usernameInputRef.current.value; const enteredPassword = passwordInputRef.current.value; const result = await signIn("credentials", { redirect: false, username: enteredUsername, password: enteredPassword, }); if (!result.error) { // handle successful authentication } else { // handle authentication error } } return ( <section className={classes.auth}> <h1>Login</h1> <form onSubmit={submitHandler}> <div className={classes.control}> <label htmlFor="username">Your Email</label> <input type="text" id="username" required ref={usernameInputRef} /> </div> <div className={classes.control}> <label htmlFor="password">Your Password</label> <input type="password" id="password" required ref={passwordInputRef} /> </div> <div className={classes.actions}> <button>Login</button> </div> </form> </section> ); } export default AuthForm;