当向/users/me
请求接收回我的用户数据时,我目前得到一个错误。从我一直在阅读的内容来看,我没有发送令牌,尽管我不确定如何在登录时从jwt/create
端点收到它时存储它。
这是从我的Auth-Test/nuxt-auth/pages/index.vue
文件:
onMounted(async () => {
const cookie = useCookie('jwt');
console.log('COOKIE: ' + JSON.stringify(cookie));
const response = await fetch('http://localhost:8000/api/auth/users/me/', {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${JSON.stringify(cookie)}`,
},
credentials: 'include'
})
const content = await response.json();
console.log(content);
})
这是我的Auth-Test/nuxt-auth/pages/login.vue
const router = useRouter();
async function submit() {
console.log(JSON.stringify({
email: user.email,
password: user.password
}))
await fetch('http://localhost:8000/api/auth/jwt/create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
email: user.email,
password: user.password
})
});
await router.push({ path: '/' });
}
谁能帮我意识到我可能做错了什么?我看了那么多的文档,怎么也想不明白。
如果你需要访问其他文件(前端和后端),这里是Github的repo。
按照这里的使用指南https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html#usage
您应该存储JWT令牌而不是使用cookie。
const router = useRouter();
async function submit() {
console.log(JSON.stringify({
email: user.email,
password: user.password
}))
const response = await fetch('http://localhost:8000/api/auth/jwt/create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
email: user.email,
password: user.password
})
});
// it's common to use localStorage to store it so when users go back to your site it's still there.
// If you don't want that you can just store it in memory.
const responseJson = await response.json();
localStorage.setItem('token', responseJson.access);
await router.push({ path: '/' });
}
那么你可以把它用作Bearer
令牌
承载身份验证(也称为令牌身份验证)是一种HTTP身份验证方案,它涉及称为承载令牌的安全令牌。"承载身份验证"的名称可以理解为"允许访问此令牌的承载者"。承载令牌是一个神秘的字符串,通常由服务器在响应登录请求时生成。当客户端向受保护的资源发出请求时,必须在授权头中发送此令牌:
授权:承载者'令牌'
onMounted(async () => {
const cookie = useCookie('jwt');
console.log('COOKIE: ' + JSON.stringify(cookie));
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:8000/api/auth/users/me/', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
credentials: 'include'
})
const content = await response.json();
console.log(content);
})