NextJS 与 next-auth ,设置从 node.js

时间:2021-07-03 10:04:02

标签: cookies next.js server-side-rendering next-auth

我使用 Nextjs 和 next-auth 在后端使用 node.js 进行身份验证。现在,我正在 node.js 中设置我的 cookie,它在邮递员中正常工作。我可以认证,没有任何问题。当涉及到 NextJs 时,由于我只从 response 返回 res.data ,它本质上包含用户数据而不是 JWT ,因此我无法将 cookie 传递给前端。因此,我没有通过 Node.js 的身份验证。我在 next-auth 上检查了 cookie 的文档,但无法使其工作。

./api/[...nextauth.ts] 的代码

import axios from 'axios'
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email", placeholder: "Your email" },
        password: { label: "Password", type: "password",placeholder: "*********" }
      },
      async authorize(credentials:any, req) {
          try
          {
              const res = await axios.post('http://node-app:4200/users/login',credentials)
              if(res.status==200)
              {
                return res.data
              }
          }
        catch(e:any){
          console.log(e.data)
        }
        return null
      }
    })
  ],
  pages: {
    signIn: '/auth/login',
    signOut: '/auth/logout',
    // error: '/auth/error', // Error code passed in query string as ?error=
    // verifyRequest: '/auth/verify-request', // (used for check email message)
    // newUser: undefined // If set, new users will be directed here on first sign in
  }
})

如果有人能指导我如何将我从 node.js 推送到 nextjs 的服务器端的 cookie 可以推送到 next 的前端,那将会很有帮助。

1 个答案:

答案 0 :(得分:0)

如果您想设置 cookie,请尝试执行以下操作:

// import ... from ...
import Cookies from 'cookies';

const getOptions = (req, res) => ({
  // Configure one or more authentication providers
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email", placeholder: "Your email" },
        password: { label: "Password", type: "password",placeholder: "*********" }
      },
      async authorize(credentials:any, req) {
        // do something

        // Set cookies
        const cookies = new Cookies(req, res);
        cookies.set('myCookie', myCookieValue);

        return null
      }
    })
  ],
  // some other configurations ...
});

export default (req, res) => NextAuth(req, res, getOptions(req, res));