Next-auth,credentials provider,jwt token --使用token作为API授权的承载

xienkqul  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(141)

我目前正在构建一个应用程序与Next.js和Next-auth与凭据提供商。我试图了解如何将我的API的限制在我的页面文件夹内,并且在尝试访问API时,以某种方式使用由next-auth创建的JWT令牌作为授权头中的承载令牌-要真正确保一个人将有权访问这个。或者这甚至不是保护你的API的最好方法?我只是想了解什么是最好的实践将是限制和保护我的API的。如果有人能指出我在正确的方向,我会很感激,因为我有点困惑时,试图找出下一个认证的文档:)
这是我的nextauth文件,如果这有帮助

[... 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);

字符串

jmp7cifd

jmp7cifd1#

你有两种方法可以做到这一点:
1.使用中间件结构简单,可以使用通配符到页面路径:

export {default } from "next-auth/middleware"

//  protecting by middleware

export const config = {
  matcher: [
     // your paths to be protected
     "/api/*"
  ]
}

字符串
1.使用服务端会话:

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})
}

相关问题