我建议使用两种常用方法中的一种。我描述了如何使用 fetch 对象,在客户端和服务器上的 express 框架。
1.在 HttpOnly cookie 中设置令牌
在服务器控制器中
module.exports.checkUser = (request, response) => {
const { token = null } = (/token=(?<token>[^;]*)/.exec(request.headers.cookie) || {}).groups || {} // Or better use cookie-parser
crudModel.verifyUser((result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.cookie('token', jwtToken, {
httpOnly: true,
// secure: true // - for secure, https only cookie
});
response.render('dashboardView'); // - now we don't need to appear token to the view, because it automatically appears in cookies in each request
}
} else {
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <- pass token
}
在客户端(在页面上),如果您使用 fetch 进行请求,则需要添加凭据参数
function makeRequest(url) {
return fetch(url, {
credentials: 'include'
})
}
更多关于这种方法的优缺点你可以阅读这个
https://stackoverflow.com/a/39833955/9051045
2。在请求标头中使用令牌并将其保存到 localStorage
html中的示例(客户端脚本)> head
function makeRequest(url, method) {
var jwtToken = localStorage.getItem('token')
var headers = {}
if(jwtToken) {
headers['Authorization'] = 'Bearer ' + jwtToken
}
return fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
headers: headers
})
}
此函数在 localStorage 中设置时使用令牌发出请求
您的控制器功能:(服务器)
module.exports.checkUser = (request, response) => {
var {token = ''} = (/Bearer\s+(?<token>.*)/.exec(request.get('Authorization') || '') || {}).groups || {}
crudModel.verifyUser( (result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.render('dashboardView', { token : jwtToken});
}
}else{
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <-pass token
}
查看(ejs):
<script>
localStorage.setItem('token', "<%= JSON.stringify(token) %>"); // <- setup token into localStorage, (but i think it's not good place for that, and would be better get token with another authorization request)
</script>
<!-- Your code below -->
<li class="nav-item active">
<a href="/user/home?authorization=Bearer "+data>Home
<span class="sr-only">(current)</span>
</a>
</li>