我是React的新手。我已经在AWS EB上使用Django后端设置了小型Web服务。它有自定义用户模型。用户登录后,大多数内容都可用。工作正常。
当我开始使用React Native制作移动应用程序时,我将Django Rest设置到同一个位置,与Web服务共享相同的数据库模型。我为它选择了令牌认证方式。它适用于移动设备上的React Native应用程序。用户通过移动应用登录后,API会返回身份验证令牌。从API获取Token后,移动应用程序与API交互,包括JSON标头中的Token。
在学习和开发React Native移动应用程序期间。我非常喜欢。所以,我想把一个小反应应用程序放到我的一个网页中,而不是编写整个单页应用程序。在这个阶段,我想到了一个问题,即我的反应应用程序如何在不再输入用户ID和密码的情况下获得身份验证令牌。
我花了好几个小时通过谷歌搜索找到任何线索,但失败了。任何人都可以给我一个提示吗?如果已经记录的网页内的应用程序如何与基于令牌身份验证的API进行交互而无需再次登录?
答案 0 :(得分:0)
我认为您可以使用cookies
或localStorage
来保存您的令牌,然后在反应部分中将此令牌排除在外。
答案 1 :(得分:0)
您可以使用localStorage
设置并获取令牌
例如:
set - > localStorage.setItem('token', 'dac43hh5r3nd23i4hrwe3i2un32u');
get - > localStorage.getItem('token');
答案 2 :(得分:0)
对于ReactJS,请查看Where to store token。您可以使用localStorage或cookies。
Cookie用法:
document.cookie = cookie_name + "=" + value + ";expires=" + expire_date + ";";
PS:过期日期应采用GMT格式。
localStorage用法:
// To set the token
localStorage.setItem('token', 'dac43hh5r3nd23i4hrwe3i2un32u');
// To get the token
localStorage.getItem('token');
Django docs for Session,并阅读this question,它会对您有所帮助。
Cookie或localStorage?
我会带饼干。为什么?因为您可以设置过期日期(例如,自动删除),域,路径和其他可能有用的东西。在localStorage上,您只需存储信息。
答案 3 :(得分:0)
在我通过长期的研究和学习解决后,我想留下我的答案。我的解决方案非常简单。 1.设置DRF会话认证启用。在setting.py中添加一些代码
REST_FRAMEWORK = {
# ...
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
2。添加'凭据:'包含“'到获取代码中以使用已登录的会话cookie进行身份验证。
await fetch(API_URL, {
credentials: "include"
})
这个解决方案解决了我的问题。
答案 4 :(得分:0)
反应您可以对调用API使用任何libray,exaxios是其中之一。首次登录时,将该令牌保存在本地存储或会话中。
现在我们必须在标头中添加该令牌,以便可以使用拦截器,即,当我们每次调用API进行拦截器调用时,在该位置,您都可以从本地存储或会话中获取令牌,并添加请求标头
下面的是拦截器的示例代码。
import axios from 'axios';
import cookie from 'react-cookies';
import * as utils from './utils';
let axios_instance = axios.create();
axios_instance.interceptors.request.use(
(configuration) => {
const config = configuration;
const authToken = cookie.load('authToken');
if (authToken) {
config.headers.Authorization = `Token ${authToken}`;
}
return config;
},
(error) => Promise.reject(error)
);
axios_instance.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status == 401) {
utils.clearCookie();
window.location.href = '/login';
return;
}
if (error.response.status == 403) {
utils.clearCookie();
window.location.href = '/login';
return;
}
if (error.response.status == 404) {
// window.location.href = '/not-found';
return;
}
if (error.response.status == 500) {
// window.location.href = '/server-error';
return;
}
return Promise.reject(error);
});
export default axios_instance;