用户登录后如何添加"Bearer"另一个路由标头?



我是编程新手,目前正在做一个小项目。

我正在尝试使用JWT实现一些授权。我在网上看了一些视频,发现大多数人都有"bearer"。+访问令牌

我浏览了一些帖子,发现我需要添加授权"持有人"我自己去,但我不太确定怎么去那里。

请帮我一下好吗?

这是我的一些代码

登录
if(response){
if(await bcrypt.compare(loginPW, response.password)){
const accessToken = jwt.sign({
email: response.email
},jwtSecret)
res.json({status: 'ok', accessToken: accessToken})
}else{
return res.json({status: 'error', error:'Invalid Credentials'})
}
}

Post请求

const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());

在请求中添加授权头和令牌

const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());

一个可能的方法是....在Post请求结果中,可以将accessToken存储在localStorage

中。
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json()).then(({accessToken})=>{

localStorage.setItem('accessToken', accessToken)
});

然后在所有请求中检索它

const anotherRequst = await fetch('/anything',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}`  // get it from localStorage
},
body: ... /// anything 
}).then((res) => res.json());

这是最简单的方法

…对于更高级的技术,请尝试使用Axios

,您可以简单地在所有请求中设置默认授权头

axios.defaults.authorization = localStorage.getItem('accessToken')

,那么你发出的任何请求都将在其头中包含accessToken

Axios.post(....)
Axios.get(...)
....

你可以在你的请求中添加'Authorization'头,就像这样

const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());

或者如果你正在处理一个大项目,你必须为每个请求发送令牌,那么你可以使用Axios,它允许你为每个请求添加公共标题,只需一行

axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

文档:https://www.npmjs.com/package/axios

最新更新