2

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.

2
  • 1
    Hey Danny..Please tell me your django server url and react url with port no. Commented Feb 26, 2021 at 18:03
  • 1
    Hey, thanks for the response. django server: http://127.0.0.1:8000/ and react localhost:3000. Commented Feb 26, 2021 at 18:31

1 Answer 1

4

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.

see this

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. I will check it out.
It worked finally. Thanks a lot. cheers!
Use this : axios.defaults.headers.common['Authorization'] = Jwt ${token}
Okay. but can you tell me what difference does it make? or is this the preferred way? thanks
No any difference between them but It's simplest way to pass JWT token for every request..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.