检查用户是否在初始请求中通过了身份验证

时间:2021-05-18 07:22:58

标签: nuxt.js amazon-cognito server-side-rendering aws-amplify

我正在为 Web 应用程序使用 nuxt + aws amplify,我需要检查用户是否已通过身份验证以根据此加载页面详细信息。我配置了放大,因此用户凭据存储在 cookie 而不是本地存储中,因此可以从 req.headers.cookie 中检索有关用户的所有信息,但下面的代码

async nuxtServerInit (props, ctx) {
  const { Auth } = withSSRContext(ctx)
  try {
    const cognitoUser = await Auth.currentAuthenticatedUser()
    console.log(cognitoUser)
  } catch(error) {
    console.error(error)
  }
},

给出 The user is not authenticated

我的放大配置:

Amplify.configure({
    sst: true,
    Auth: {
        identityPoolId: process.env.IDENTITY_POOL_ID,
        userPoolId: process.env.USER_POOL_ID,
        userPoolWebClientId: process.env.USER_POOL_CLIENT_ID,
        region: 'eu-central-1',
        mandatorySignIn: false,
        cookieStorage: {
            domain: isDev ? 'localhost;' : '.website.my',
            path: '/',
            expires: 1,
            sameSite: 'strict',
            secure: !isDev
        },
        authenticationFlowType: 'USER_PASSWORD_AUTH'
    }
})

登录和身份验证在客户端工作正常。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

我发现问题出在配置上,当使用 ssr: true 时,您不能为 cookie 添加手动配置。 所以这里的解决方案就是删除这个块

cookieStorage: {
  domain: isDev ? 'localhost;' : '.website.my',
  path: '/',
  expires: 1,
  sameSite: 'strict',
  secure: !isDev
},