python - cookie 不在浏览器 django rest 中创建
问题描述
我正在尝试通过 cookie 中的访问令牌进行授权。但是我在设置 cookie 时遇到了问题。我在登录时设置了cookie:
class ApiLoginView(APIView):
permission_classes = [AllowAny]
def post(self, request, ):
password = request.data.get("password")
email = request.data.get("email")
user = authenticate(username=email, password=password)
if user:
try:
user.auth_token.delete()
except Exception as e:
pass
Token.objects.create(user=user)
response = Response()
response.set_cookie(key='access_token', value=user.auth_token.key, httponly=True)
response.data = {"result": True, "token": user.auth_token.key}
print(request.COOKIES)
auth.info("user {} login".format(user))
return response
else:
return JsonResponse({"error": "Wrong Credentials"}, status=status.HTTP_400_BAD_REQUEST)
如果我授权邮递员,一切顺利,cookie 已设置。
print(request.COOKIES)
{'csrftoken': 'JZ1OOBZ0Ilxwo8Zt7DR0SbQ8MUMyNjiPhKYOIUQqY3OeXBEheeUoIa9MSI5S0HXG', 'access_token': 'd67ab794f8752ef02bcba5418bef2c6f87cb74f2'}
但是如果你通过前端来做,我只会得到这个
{'_ym_uid': '1612967974591822622', '_ym_d': '1614006098'}
我的前端请求:
const response = await fetch("httpS://blablabla/api/auth/login", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
我还配置了 cors 标头CORS_ALLOW_CREDENTIALS = True
解决方案
我明白这是怎么回事,cookie 在 chrome 中的 localhost 上不起作用
推荐阅读
- php - 在谷歌应用引擎的 laravel 过山车 cms 中使特定文件夹可写
- angular6 - "ng generate application xyz" CLI not woking
- php - 在php中登录成功后如何重定向到另一个页面?
- dialogflow-es - DialogFlow:“添加响应”在 Web 演示中不起作用
- angular - Angular:用于显示树的递归组件
- opencv - 如何获得相机校准矩阵?
- python - Docker 容器在启动时在 requirements.txt 中安装新包
- python - Django - TypeError:“NoneType”类型的对象在进行分页时没有发生 len()
- node.js - 我无法通过 CMD 使用 npm 安装 httpster
- swift - 如何只设置一次导航控制器设置