NextJS 与 next-auth,设置从 node.js 接收的 cookie

Ank*_*rma 9 cookies server-side-rendering next.js next-auth

我正在使用 Nextjs 和 next-auth 在后端使用 node.js 进行身份验证。现在,我在 node.js 中设置 cookie,它在 postman 中可以正常工作。我可以验证,没有任何问题。当谈到 NextJs 时,由于我只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
  }
})
Run Code Online (Sandbox Code Playgroud)

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

小智 6

我认为索尔·蒙蒂利亚另一个问题中回答了这个问题。我复制并粘贴他的答案:

经过一段时间的研究,我已经弄清楚了。

我必须以导出 NextAuth 的方式对 /pages/api/auth 进行更改。

代替

export default NextAuth({
    providers: [
       ...
    ]

})

Run Code Online (Sandbox Code Playgroud)

像这样导出它,这样我们就可以访问请求和响应对象

export default (req, res) => {
    return NextAuth(req, res, options)
}
Run Code Online (Sandbox Code Playgroud)

但是要在选项对象中访问它们,我们可以将其设为回调

const nextAuthOptions = (req, res) => {
    return {
        providers: [
           ...
        ]
    }
}

export default (req, res) => {
    return NextAuth(req, res, nextAuthOptions(req, res))
}
Run Code Online (Sandbox Code Playgroud)

要将 cookie 从后端发送回前端,我们必须在响应中添加“Set-Cookie”标头

res.setHeader('Set-Cookie', ['cookie_name=cookie_value'])
Run Code Online (Sandbox Code Playgroud)

完整的代码是

import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

const nextAuthOptions = (req, res) => {
    return {
        providers: [
           CredentialsProvider({
                async authorize(credentials) {
                   try {                      
                        const response = await axios.post('/api/login', {
                            username: credentials.username,
                            password: credentials.password
                        })

                        const cookies = response.headers['set-cookie']

                        res.setHeader('Set-Cookie', cookies)
                        
                        return response.data
                    } catch (error) {
                        console.log(error)
                        throw (Error(error.response))
                    } 
                }
           })
        ]
    }
}

export default (req, res) => {
    return NextAuth(req, res, nextAuthOptions(req, res))
}
Run Code Online (Sandbox Code Playgroud)


小智 -3

如果你想设置 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));
Run Code Online (Sandbox Code Playgroud)