authorize函数nextauthjs typescript出错

8fq7wneg  于 2023-10-18  发布在  TypeScript
关注(0)|答案(2)|浏览(134)

我试图在nextAuth中使用凭据提供程序,NextJS应用程序(“next”:“13.5.4”,“下一个验证”:“^4.23.2”)。我用 typescript 写这篇文章,在正确获得函数方面遇到了问题。
这是我的api\auth\[...nextauth]\route.ts文件

CredentialsProvider({
        name: 'credentials',
        credentials: {},

        async authorize(credentials: any) {
            const {email, password} = credentials

            try {
                const user = await prisma.user.findFirst({
                    where: {
                        email: email
                    }
                })

                if (!user) {
                    return null
                }

                const passwordMatch = await bcrypt.compare(password, user.password)
                if (!passwordMatch) {
                    return null
                }

                return user
            } catch (error) {
                console.error("ERROR AuthOptions: ", error);                    
            }
        },
    }),

这是我得到的错误

Type '(credentials: any) => Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type '(credentials: Record<never, string>, req: Pick<RequestInternal, "body" | "query" | "headers" | "method">) => Awaitable<User>'.
  Type 'Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type 'Awaitable<User>'.
    Type 'Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type 'PromiseLike<User>'.
      Types of property 'then' are incompatible.
        Type '<TResult1 = { id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }, TResult2 = never>(onfulfilled?: (value: { id: number; firstName: string; ... 5 more ...; updatedAt: Date; }) => TResult1 | PromiseLike<...>, onrejected?: (reason: an...' is not assignable to type '<TResult1 = User, TResult2 = never>(onfulfilled?: (value: User) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => PromiseLike<...>'.
          Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
            Types of parameters 'value' and 'value' are incompatible.
              Type '{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }' is not assignable to type 'User'.
                Types of property 'id' are incompatible.
                  Type 'number' is not assignable to type 'string'.

我的ts.config文件

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

如何解决此问题?

arknldoa

arknldoa1#

错误消息指出方法authorize使用了错误的签名。
两种可能的修复方法:
1.您需要更改credentials: any以匹配方法authorize的输入参数签名

(credentials: Record<never, string>, req: Pick<RequestInternal, "body" | "query" | "headers" | "method">)
  1. authorize的返回类型必须是Awaitable<User>。您正在返回user
3phpmpom

3phpmpom2#

我想你需要附加信息字段凭据:{},示例:

import CredentialsProvider from "next-auth/providers/credentials";
...
providers: [
  CredentialsProvider({
    // The name to display on the sign in form (e.g. "Sign in with...")
    name: "Credentials",
    // `credentials` is used to generate a form on the sign in page.
    // You can specify which fields should be submitted, by adding keys to the `credentials` object.
    // e.g. domain, username, password, 2FA token, etc.
    // You can pass any HTML attribute to the <input> tag through the object.
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: { label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      // Add logic here to look up the user from the credentials supplied
      const user = { id: "1", name: "J Smith", email: "[email protected]" }

      if (user) {
        // Any object returned will be saved in `user` property of the JWT
        return user
      } else {
        // If you return null then an error will be displayed advising the user to check their details.
        return null

        // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
      }
    }
  })
]
...

你可以看到:https://next-auth.js.org/providers/credentials

相关问题