我目前正在使用 Next.js 和 Next-auth 以及凭证提供程序构建一个应用程序。 我试图了解如何限制我的 api 在我的页面文件夹内,并在尝试访问 api 时以某种方式使用由 next-auth 创建的 JWT 令牌作为授权标头中的不记名令牌 - 真正确保人们的安全有权访问此内容。或者这甚至不是保护你的 api 的最佳方法?我只是想了解限制和保护我的 API 的最佳实践是什么。如果有人能指出我正确的方向,我将不胜感激,因为在尝试找出下一个身份验证的文档时我有点困惑:)
如果有帮助的话,这是我的下一个身份验证文件
[...nexthauth].tsx 文件
import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
type: "credentials",
credentials: {},
async authorize(credentials, req) {
const { username: inputUsername, password: inputPassword } =
credentials as {
username: string;
password: string;
};
//Logic for checking user against Database.
// User not found in database
if (
inputUsername !== responseUsername ||
inputPassword !== responsePassword
) {
throw new Error("Invalid credentials");
}
//If everything is fine
return { id: responseId, name: responseUsername, email: responseEmail };
},
}),
],
pages: {
signIn: "/auth/login",
},
};
export default NextAuth(authOptions);
您有两种方法可以做到这一点:
使用中间件结构简单,可以使用通配符来分页路径:
export {default } from "next-auth/middleware"
// protecting by middleware
export const config = {
matcher: [
// your paths to be protected
"/api/*"
]
}
使用服务器端会话:
export async function GET(request) {
// protected API route
const session = await getServerSession(authOptions)
if (!session) {
return new NextResponse(JSON.stringify({error: "you are not allowed here"}), {
status: 403,
})
}
return NextResponse.json({authenticated: !!session})
}