我目前正在使用 next-auth v5,并尝试将 accessToken 与用户信息一起存储在我的 auth.ts 文件中。但是,我在实现这一点时遇到了一些困难。我尝试过...
我目前正在使用 next-auth v5,并尝试将 accessToken 与用户信息一起存储在我的 auth.ts 文件中。但是,我在实现这一点时遇到了一些困难。我尝试了各种方法,但到目前为止还没有成功。
这是我的 auth.ts 文件:
"use server"
import {z} from "zod"
import NextAuth, { AuthError, User } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { AuthConfig } from '@/app/auth.config';
import axios, { AxiosResponse } from "axios";
import type { DefaultSession } from 'next-auth';
declare module 'next-auth' {
interface Session {
user: {
accessToken: string;
} & DefaultSession['user'];
}
interface User {
accessToken: string;
}
}
let authURL = process.env.NEXT_PUBLIC_AUTH_URL
async function getUser(username: string,password:string): Promise<User | undefined> {
let credentials = {
username : username,
password : password
}
try {
const response : AxiosResponse<User> = await axios.post(`${authURL}/api/v1/User/Login`, credentials);
return response?.data;
} catch (error : any) {
throw new Error("Failed to authenticate user.")
}
}
//authenticate
export async function authenticate(
prevState: string | undefined,
formData: FormData,
) {
try {
await signIn('credentials', formData);
} catch (error) {
if (error instanceof AuthError) {
return 'Invalid Credentials.';
}
throw error;
}
}
export const { auth, signIn, signOut } = NextAuth({
...AuthConfig,
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ username: z.string(), password: z.string().min(6)})
.safeParse(credentials);
if (parsedCredentials.success) {
const { username, password} = parsedCredentials.data;
const user = await getUser(username, password);
if (!user)
return null;
console.log("User => ", user)
return {
id: user.id,
name: user.name,
email: user.email,
accessToken: user.accessToken
};
}
console.log('Invalid credentials')
return null;
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.accessToken = user.accessToken;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.accessToken = token.accessToken as string;
}
return session;
},
},
});
请帮忙,我犯了什么错误?如果有人能提供一些指导或建议,说明如何在 next-auth v5 中正确存储带有用户信息的 accessToken,我将不胜感激。任何示例或代码片段都对我理解实现这一点的正确方法非常有帮助。提前感谢您的帮助!