我在 stackoverflow 中阅读了很多文章,也看过很多 youtube 视频,但没有找到演示将 jwt 保存到 localstorage的流程的示例代码- 使用授权标头发送回服务器以验证.
这是我想要做的。
当客户端登录到服务器时,服务器给出令牌并将其保存到客户端localStorage
(或sessionStorage
)。
每当客户端调用只能使用令牌访问的 api 时,客户端从 取回令牌localStorage
,并将该令牌与授权标头(req.headers.[x-access-token]
或req.headers.[authorization]
)一起发送到服务器。
但是我读过的所有文章都在用邮递员解释这个问题,邮递员没有说明如何将其存储到localStorage
授权标头中。
我是否必须localStorage.setItem
在服务器将令牌提供给客户端时使用,localStorage.getItem
并在将该令牌发送回服务器之前使用 and和new Headers()
withappend()
或axios
之前使用?
示例不必针对快速用户,但我想了解一下想法。
您可以将 jwt 令牌存储在 localstorage 中,并且在进行 API 调用时,您可以将令牌作为令牌添加到标头中。如果您使用的是 axios,您可以将您的令牌附加到这样的标头上。这里令牌存储在 localstorage 中,密钥为“jwtToken”
axios.post('http://yourendpoint',data,{ headers: { Authorization:localStorage.getItem('jwtToken') } })
.then(response=> console.log(response))
.catch(error => console.log(error));
};
Run Code Online (Sandbox Code Playgroud)
小智 5
很简单,关注我即可
首先,您必须将令牌(或访问令牌)保存到本地存储,在发送登录请求时在登录组件中执行以下操作:
signin:function() {
axios.post('http://Somthing/log-in/',{
username: this.username,
password: this.password,
})
.then( (response) => {
let token = response.data.access;
localStorage.setItem("SavedToken", 'Bearer ' + token);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
(this.$router.push({name:'HomePage'}));
})
Run Code Online (Sandbox Code Playgroud)
所以现在的问题是,每当您刷新主页时,您都会收到 401 错误,解决方案是:只需将以下内容添加
{ headers: { Authorization:localStorage.getItem('SavedToken') }}
到每个需要标头中的令牌的请求的末尾,如下所示:
axios.get('http://Something/', { headers: { Authorization:localStorage.getItem('SavedToken') }})
.then(response =>{
//something
})
Run Code Online (Sandbox Code Playgroud)
请注意,我在本说明中使用的令牌是SIMPLEJWT,如果您使用其他东西,也许您必须将 “Bearer”更改为其他东西。
归档时间: |
|
查看次数: |
11738 次 |
最近记录: |