1

我正在使用 NextJs getInitialProps 尝试刷新访问令牌。

if(!access_token && ctx.req) {
  try {
    await axios({
      method: 'GET',
      url: 'http://localhost:3000/api/refresh_token',
      withCredentials: true,
      headers: refresh_token ? { cookie: ctx.req.headers.cookie } : {}
    })

    console.log(ctx.res.headers)
  } catch (error) {
    console.log(error.response)
  }
}

这是 api 端点:

import axios from 'axios'
import { serialize } from 'cookie'

export default async (req, res) => {
  try {
    const response = await axios.post('http://localhost/oauth/token', {
      grant_type: 'refresh_token',
      refresh_token: req.cookies.refresh_token,
      client_id: process.env.CLIENT_ID,
      client_secret: process.env.CLIENT_SECRET,
      scope: '*',
    })

    const { access_token, refresh_token, expires_in } = response.data

    res.setHeader('Set-Cookie', [
      serialize('access_token', access_token, { path: '/', maxAge: expires_in, httpOnly: true, sameSite: true }), 
      serialize('refresh_token', refresh_token, { path: '/', httpOnly: true, sameSite: true })
    ])

    return res.status(200).json({ message: 'yess' })
  } catch (error) {
    res.status(error.status || 500).end(error.response.data.message)
  }
}

但是当我记录响应标头时,cookie 没有设置。Chrome 也不显示 cookie。我错过了一步吗?也许是因为它的服务器端渲染我必须用另一种方式来做?老实说,我已经坚持了 3 天了,我已经尝试了一切(至少我是这么认为的)但没有成功。它困扰着我,因为我不知道在 NextJs 中设置正确的身份验证。

4

0 回答 0