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. 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. 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.
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
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.
set backend and frontend under same IP . ex. backend is
localhost:8000
py manage.py runserver localhost:8000
and frontend is(By default):
localhost:3000
different ports same Ip .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.