【发布时间】:2021-06-29 16:55:02
【问题描述】:
与Next.js 和Django Rest Framework 合作,我正在使用JWT 对用户进行身份验证。首先,当用户成功登录页面时,会向浏览器发送一个 cookie(包含 JWT 令牌)。当用户尝试访问特定页面时,此 cookie 用于验证请求。我在浏览器中存储 cookie 时遇到问题。
姜戈 |登录功能
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def login(request):
...
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True, max_age=86400)
response.data ={
'message': 'success',
}
return response
这就是我获取 /api/login 的方式
下一个 |登录.js
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
data.append('X-CSRFToken', csrftoken);
data.append('mode', 'same-origin');
data.append('Content-Type', 'application/json');
var config = {
method: 'post',
credentials: 'include', #I'm probably having issues with this
url: 'http://localhost:8000/api/login',
data : data
};
axios(config)
.then(res=> {
console.log('success'); #I got logged, but cookie is not stored
})
.catch(
error=>{this.setState({isError:true})}
);
如您所见,在它们中,我都收到了名为 JWT 的 cookie。但它没有存储在浏览器中。 提前感谢您的时间和回答!
【问题讨论】:
-
是的,我可以看到
Set-Cookie,我已经更新了问题。 -
cookie 安全吗?
-
@UdenduAbasili 检查 Postman 中的 cookie 选项卡,
JWTcookie 显示为不安全但HttpOnly = True。如何保护此 cookie?我想看看这是否能解决我的问题 -
没有安全 cookie 仅在网站使用 ssl 时有效,我假设您的网站不使用。我想确认一下,因为如果您对不安全的网站使用secure true,有时这可能会成为问题
-
我没有使用 SSL,目前正在使用 localhost