[英]Django REST and React - JWT Cookie not getting set in browser but working with postman
Hey guys I am stuck trying to solve the issue with django set_cookie
, I can't find the cookie in the browser and it doesn't work but works with postman.嘿伙计们,我一直试图用 django
set_cookie
解决问题,我在浏览器中找不到 cookie,它不起作用,但适用于 postman。 I went through some of the SO answers and found that I had to provide withCredentials:true
in the frontend and I have done that, but still it doesn't work.我浏览了一些 SO 答案,发现我必须在前端提供
withCredentials:true
并且我已经做到了,但它仍然不起作用。 This is the code I have, can someone tell me the error in this?这是我的代码,有人可以告诉我其中的错误吗?
I want to have the cookies set at login, as of now I am storing the token in local storage and I came to know it is not a safe option.我想在登录时设置 cookies,到目前为止,我将令牌存储在本地存储中,我知道这不是一个安全的选择。
def post(self, request, format=None):
data = request.data
response = Response()
username = data.get('username', None)
password = data.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
data = get_tokens_for_user(user)
response.set_cookie(
key = settings.SIMPLE_JWT['AUTH_COOKIE'],
value = data["access"],
expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
)
csrf.get_token(request)
response.data = {"Response": "Login Successful", "data":data,}
return response
else:
return Response({"error": "User is not active"}, status=status.HTTP_404_NOT_FOUND)
else:
return Response({"error": "Invalid credentials"}, status=status.HTTP_404_NOT_FOUND)
react front-end反应前端
const handleSubmit = (e) => {
e.preventDefault();
axiosInstance
.post(url, {
username: formData.username,
password: formData.password,
})
// .then((res) => {
// localStorage.setItem('access_token', res.data.access);
// localStorage.setItem('refresh_token', res.data.refresh);
// })
.then(()=> {
history.push('/');
window.location.reload();
})
};
axiosInstance axiosInstance
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
// Authorization: localStorage.getItem('access_token')
// ? 'JWT ' + localStorage.getItem('access_token')
// : null,
'Content-Type': 'application/json',
accept: 'application/json',
},
withCredentials: true
});
Thank you.谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.