使用 next-auth 包和 auth0 提供程序进行 Next.js 应用程序身份验证

问题描述 投票:0回答:1

我找不到使用 next-auth 包设置提供者 auth0 的详细说明。

https://next-auth.js.org/providers/auth0看起来很差。

是否可以将 next-auth 和自定义 Auth0 应用程序与自定义登录和注册页面配对?

我用:

next.js 14.0.3 (App Directory)
next-auth 4.24.4

构建我自己的解决方案的基础信息。

next.js server-side-rendering auth0 next-auth
1个回答
0
投票

欢迎来到 Stack Overflow。是的,这是可能的,而且可行。

这是一个例子:

app/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcrypt";

const handler = NextAuth({
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {},
        password: {},
      },
      async authorize(credentials, req) {
        //  Get User from database

       // Compare passwords
        const comparePasswords = await compare(
          credentials?.password || "",
          user.password
        );
       // Login user if password match
        if (comparePasswords) {
          return {
            id: user.id,
            email: user.email,
          };
        }
        return null;
      },
    }),
  ],
});

export { handler as GET, handler as POST };

之后您可以使用 next-auth useSession 调整 UI

import { signOut, useSession } from "next-auth/react";

const MainHeader = () => {
  const { data: session } = useSession();


  return (
    <div>
     {!session ? <Link href="/login">Login</Link> : (
     <div onClick={() => signOut()}> Logout </div> 
      )}
    </div>
  )
}
export default MainHeader

如果您需要更多帮助,我建议观看此 YouTube 教程

© www.soinside.com 2019 - 2024. All rights reserved.