在 Cookie 中存储了 JWT Access Key 但仍然无法访问 API
Stored JWT Access Key in Cookie but still can't access API
在我的 nextjs React 应用程序中,我的登录页面有这个来存储我的 cookie:
axios
.post(apiUrl, data)
.then(response => {
console.log(response.data);
const token = response.data.access;
Cookies.set('jwtCookie', token, { expires: 1 });
Router.push('/');
setShowLoading(false);
props.history.push('/show/' + response.data._id);
})
.catch(error => setShowLoading(false));
我已成功从我的后端接收到访问密钥,我的 cookie 可以在 Chrome 上开发工具的应用程序部分看到。
但是,从这一点来看,我有点困惑要做什么才能让我访问需要身份验证的页面。
我有一个页面,我在其中使用 axios 发出获取请求:
const user = await axios
.get(`http://localhost:8000/api/users/${username}/complete/`, { withCredentials: true })
.then(function(response) {
return response.data;
});
如何告诉我的后端我的访问密钥存储在一个名为 jwtCookie 的 cookie 中,以便它可以让我执行 get 请求?我正在使用 Django Rest Framework 并将此页面上的权限 class 设置为 IsAuthenticated。
我知道我的知识在某处存在差距,我希望有人能帮助我弥补这一差距。谢谢!
API 可以通过多种方式进行身份验证,并且 DRF 支持多种方式。您正在使用令牌身份验证,在这种情况下,您需要在 Authorization
HTTP header.
中提供令牌
您可以像这样指定全局 axios 默认值,
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
创建实例时可以这样设置,
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {'Authorization': AUTH_TOKEN}
});
或者之后,
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
在我的 nextjs React 应用程序中,我的登录页面有这个来存储我的 cookie:
axios
.post(apiUrl, data)
.then(response => {
console.log(response.data);
const token = response.data.access;
Cookies.set('jwtCookie', token, { expires: 1 });
Router.push('/');
setShowLoading(false);
props.history.push('/show/' + response.data._id);
})
.catch(error => setShowLoading(false));
我已成功从我的后端接收到访问密钥,我的 cookie 可以在 Chrome 上开发工具的应用程序部分看到。
但是,从这一点来看,我有点困惑要做什么才能让我访问需要身份验证的页面。 我有一个页面,我在其中使用 axios 发出获取请求:
const user = await axios
.get(`http://localhost:8000/api/users/${username}/complete/`, { withCredentials: true })
.then(function(response) {
return response.data;
});
如何告诉我的后端我的访问密钥存储在一个名为 jwtCookie 的 cookie 中,以便它可以让我执行 get 请求?我正在使用 Django Rest Framework 并将此页面上的权限 class 设置为 IsAuthenticated。
我知道我的知识在某处存在差距,我希望有人能帮助我弥补这一差距。谢谢!
API 可以通过多种方式进行身份验证,并且 DRF 支持多种方式。您正在使用令牌身份验证,在这种情况下,您需要在 Authorization
HTTP header.
您可以像这样指定全局 axios 默认值,
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
创建实例时可以这样设置,
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {'Authorization': AUTH_TOKEN}
});
或者之后,
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;