使用 Vue3 amplify 针对 AWS Cognito 对用户进行身份验证

时间:2021-01-01 15:49:27

标签: amazon-cognito aws-amplify vuejs3

我正在使用 vue3 并设置了一个 AWS 用户池 (amazoncognito.com)。 目标是使用用户名和密码针对 Cognito 对用户进行身份验证,并接收 OAuth2 令牌以验证针对 AWS API 网关发出的 API 请求。

挑战: 似乎 AWS amplify 不适用于最新的 vue3 版本。它只显示用户未登录但不显示任何登录或注销按钮 - 无论配置如何。

我感兴趣的潜在解决方案(优先顺序)

main.js

import { createApp } from 'vue'
import App from './App.vue'
import Amplify from 'aws-amplify';
import Auth from '@aws-amplify/auth';

Amplify.configure({
  Auth: {
      identityPoolId: 'eu-central-1_REST-OF-ID',
      region: 'eu-central-1',
      userPoolWebClientId: '4t49u0pu0skkREST-OF-ID',
      mandatorySignIn: false,
      cookieStorage: {
            domain: 'PREFIX.auth.eu-central-1.amazoncognito.com',
            path: '/',
            expires: 365,
            sameSite: "lax",
            secure: true
        },
      authenticationFlowType: 'USER_PASSWORD_AUTH',
      oauth: {
          domain: 'PREFIX.auth.eu-central-1.amazoncognito.com',
          scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
          redirectSignIn: 'http://localhost:3000/',
          redirectSignOut: 'http://localhost:3000/',
          responseType: 'code' // or 'token', note that REFRESH token will only be generated when the responseType is code
      }
  }
});

import { createStore } from 'vuex'
const store = createStore({
    state() {
      return {
        entries: []
      };
    },
    mutations: {
      addTime(state, item) {
        state.entries.push(item);
      }
    }
});

createApp(App).use(store, Amplify, Auth).mount("#app");
    

在 App.vue 中

  <template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
  <AddTime/>
  <amplify-authenticator>
    <div>
    Inside Authenticator
    <amplify-sign-in></amplify-sign-in>
      <amplify-sign-out></amplify-sign-out>
    </div>
  </amplify-authenticator>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import AddTime from './components/AddTime.vue';

export default {
  name: 'App',
  components: {
    HelloWorld,
    AddTime,
  }
}
</script>
  1. 有没有人能够在 vue3 中使用 AWS 放大身份验证模块?
  2. 如何使用 vue3 访问 Cognito OAuth 2.0 授权服务器并获取(通过发布用户放置的凭据来验证和接收令牌?

2 个答案:

答案 0 :(得分:0)

事实证明,即使在发布几个月后,vue3 也不受支持。 请参阅:https://github.com/aws-amplify/amplify-js/issues/6756

答案 1 :(得分:0)

Amplify 现在支持 Vue3,但它仍处于早期阶段。最大的变化是你不再使用 ui-vue 包。您需要使用 ui 组件:

yarn add aws-amplify @aws-amplify/ui-components

AWS has an auth example for you to use on their website. 确保选择示例中的 Vue3 选项卡。我还可以确认这在 ionic 应用程序中也对我有用。