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

Check if the user is authenticated on the initial request

我正在为 Web 应用程序使用 nuxt + aws amplify,我需要检查用户是否经过身份验证以加载页面详细信息。我配置了 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'
    }
})

客户端的登录和授权工作正常。

看来您已正确配置 Amplify。我建议您阅读以下指南并仔细检查您的配置...

  1. https://docs.amplify.aws/start/getting-started/data-model/q/integration/next#api-with-server-side-rendering-ssr

  2. AWS Cognito cookie storage

  3. https://github.com/aws-amplify/amplify-js/issues/1735

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

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