Skip to content

Instantly share code, notes, and snippets.

@mrichman
Last active January 16, 2023 13:11
Show Gist options
  • Save mrichman/45389684d4c9ea40240f362cea99302f to your computer and use it in GitHub Desktop.
Save mrichman/45389684d4c9ea40240f362cea99302f to your computer and use it in GitHub Desktop.
Cognito Hosted UI + Vue.js
<template>
<div>
<b-container>
<b-row align-h="center">
<div v-if="!signedIn">
<b-button variant="success" @click="signIn">Sign in with Cognito</b-button>
</div>
<div v-if="signedIn">
<h4>Welcome, {{ username }}!</h4>
<b-button variant="danger" @click="signOut">Sign out</b-button>
</div>
</b-row>
</b-container>
</div>
</template>
<script>
import { Auth, Hub } from "aws-amplify";
export default {
name: "HelloWorld",
props: {},
data() {
return {
signedIn: false,
username: String
};
},
methods: {
signIn: () => {
console.log("HelloWorld signIn()");
Auth.federatedSignIn(); // Cognito is the default provider
},
signOut: () => {
console.log("HelloWorld signOut()");
Auth.signOut()
.then(data => {
console.log(data);
})
.catch(err => console.log(err));
}
},
mounted() {
console.log("HelloWorld mounted()");
Hub.listen("auth", ({ payload: { event, data } }) => {
console.log(`Auth event: ${event}`);
switch (event) {
case "signIn":
console.log("signIn data: " + JSON.stringify(data));
this.signedIn = true;
this.username = data.username;
break;
case "signOut":
this.signedIn = false;
this.username = null;
break;
}
});
Auth.currentAuthenticatedUser()
.then(user => {
console.log("Username: " + user.username);
console.log("Refreshing access and id tokens");
Auth.currentSession()
.then(data => console.log(data))
.catch(err => console.log("Error refreshing tokens: " + err));
this.signedIn = true;
this.username = user.username;
})
.catch(err => console.log("Auth.currentAuthenticatedUser(): " + err));
}
};
</script>
<style scoped>
</style>
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Amplify, * as AmplifyModules from 'aws-amplify'
import { AmplifyEventBus, AmplifyPlugin } from 'aws-amplify-vue'
import { BootstrapVue } from 'bootstrap-vue'
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
Vue.use(AmplifyPlugin, AmplifyModules)
Vue.use(BootstrapVue)
Vue.config.productionTip = false
Amplify.configure({
Auth: {
region: 'us-east-1',
userPoolId: 'us-east-1_XXXXXXXX',
userPoolWebClientId: 'YOUR COGNITO APP CLIENT ID',
oauth: {
domain: 'YOUR COGNITO DOMAIN',
scope: ['email', 'profile', 'openid'],
redirectSignIn: 'http://localhost:8080/',
redirectSignOut: 'http://localhost:8080/',
responseType: 'code'
}
},
});
AmplifyEventBus.$on('authState', info => {
console.log(`Here is the auth event that was just emitted by an Amplify component: ${info}`)
});
new Vue({
router,
render: h => h(App)
}).$mount('#app')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment