Netlify设置
首先进入Netlify开启Identity。
Netlify identity widget
然后可以使用netlify-identity-widget。
首先在html的head标签中添加:
markup
<script type="text/javascript" src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
FrontEnd
添加注册/登录按钮
接下来在body标签中添加:
markup
<body>
<!-- Add a menu:
Log in / Sign up - when the user is not logged in
Username / Log out - when the user is logged in
-->
<div data-netlify-identity-menu></div>
<!-- Add a simpler button:
Simple button that will open the modal.
-->
<div data-netlify-identity-button>Login with Netlify Identity</div>
</body>
保护相关资源
以Vue.js为例:
markup
<template>
<div v-if="isAuthenticated">
这里为受保护资源
</div>
<div v-else>
这里是公开的资源
</div>
</template>
<script>
export default {
name: 'NetlifyIdentityDemo',
data() {
return {
studentNameInput = '';
students = [],
isAuthenticated: false,
token: ""
}
},
async created() {
const thisObj = this;
netlifyIdentity.on('init', async user => {
if(user) {
thisObj.token = user.token.access_token;
await thisObj.fetchStudents();
thisObj.isAuthenticated = true;
}
})
netlifyIdentity.on('login', user => {
if(user) {
thisObj.token = user.token.access_token;
thisObj.isAuthenticated = true;
}
})
netlifyIdentity.on('logout', () => {
if(user) {
thisObj.isAuthenticated = false;
thisObj.studentNameInput = '';
thisObj.students = [];
thisObj.token = '';
}
})
},
methods: {
async listStudents() {
let response = await fetch("./netlify/functions/liststudents", {
headers: {
"Authorization": `Bearer ${this.token}`
}
});
}
}
}
</script>
测试
将以上代码部署到Netlify,访问产品模式下的应用。
打开Chrome开发者工具,选择Storage =》 Local Storage =》选择access_token (JWT token)
访问 https://jwt.io 将上一步的access_token复制过来,就可以看到解码后的相关用户信息。
Backend
liststudents.js
注意在user对象中有一个sub属性,可以作为student对象的标识符
JavaScript
exports.handler = async(event, context) => {
let user = context.clientContext.user;
let studetns = await dbService.listStudents();
students = students.filter(s => s.studentId === user.sub);
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Content-Type": "application/json"
},
body: JSON.stringify(students)
}
}