我最近在我的Nuxt.js网站上集成了AWS Amplify,我选择不通过amplify-cli。我的身份验证工作得很好,但你必须在/login.vue页面上自己去。如果用户没有登录,我想通过简单地在登录页面上重定向用户来强制进行身份验证。
对于中间件部分,我尝试了不同的方法。下面是我所做的:
// middleware/authenticated.js
import { Auth } from 'aws-amplify'
export default function ({ redirect }) {
if (Auth.currentAuthenticatedUser() == undefined) {
return redirect('/login')
}
}// plugins/Amplify.js
import Vue from 'vue'
import Amplify, * as AmplifyModules from 'aws-amplify'
import { AmplifyPlugin, components } from 'aws-amplify-vue'
Amplify.configure({
Auth: {
identityPoolId: 'eu-west-1:xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
mandatorySignIn: true,
region: 'eu-xxx-x',
identityPoolRegion: 'eu-xxxx-x'
}
})
Vue.use(AmplifyPlugin, AmplifyModules)发布于 2019-12-02 00:43:59
避免使用中间件,因为它在第一次加载时在服务器上呈现。AWS amplify在服务器端不可用。另一种方法是使用mixins:
mixins/authentication.js
import { Auth } from 'aws-amplify'
export default {
async mounted() {
if (this.$store.state.account.authorized) {
return
}
try {
let user = await Auth.currentAuthenticatedUser({ bypassCache: false })
if (!user) {
this.$router.push('/login')
}
} catch (err) {
this.$router.push('/login')
}
}
}然后在您希望进行身份验证的每个页面中导入(或在某个布局中)。
import authentication from "@/mixins/authentication.js";
...
export default {
mixins: [authentication],
...这可能会导致第二次'blink‘断开,直到重定向回登录页面,因为代码发生在'mounted’上。
任何更优雅的建议都将不胜感激!
发布于 2020-03-21 10:10:49
这可能会对你有所帮助:https://stackoverflow.com/a/60783792/3474490
然后在middleware/auth.js中进行身份验证
export default function({ store, route, redirect }) {
return store.$Amplify.Auth.currentAuthenticatedUser()
.catch(() => {
this.$router.push('/')
})
.then((user) => {
// Set user in store
store.commit('setUser', user)
// Requires authentication
if (route.meta.some((meta) => meta.requiresAuth)) {
if (!user) redirect('/login/')
}
// Requires to be anonymous
if (route.meta.some((meta) => meta.requiresAnonymous)) {
if (user) redirect('/dashboard/')
}
})
}然后在页面中,我只需要设置meta标签requiresAuth或requiresAnonymous,如果适用。
https://stackoverflow.com/questions/58919633
复制相似问题