3

I am currently developing a React-Django App and using JWTs for authentication.

After a little research I found out that storing JWTs in client is not safe(XSS and XSRF) and most of the people advice that I should store them in server-side with HttpOnly cookies but nobody tells how to do it. So can anybody help with that?

I got jwt-cookies as response but it is not saved in the browser. response cookies

altF4
  • 269
  • 4
  • 19

3 Answers3

3

You can set cookie with set_cookie() method.

For example:

...
response = Response(serializer.data)
response.set_cookie('token', serializer.data['token'], httponly=True)
return response

Good article about where to store JWT (and how to do it) here.

  • Well I'm using dj-rest-auth package and in settings.py if I enable `REST_USE_JWT = True` it automatically uses this method to response with jwt cookie.(https://github.com/jazzband/dj-rest-auth/blob/master/dj_rest_auth/views.py) So I got jwt cookie after login request in response cookies section but it is not saved in browser, thus after refreshing the page it goes away. – altF4 Aug 19 '20 at 20:29
  • 1
    Hmm, maybe [this](https://stackoverflow.com/questions/46359195/set-django-rest-frmework-jwt-in-cookies) question will help. – Timofey Katalnikov Aug 19 '20 at 20:34
  • Unfortunately I already tried that. Maybe I should do it manually instead of letting dj-rest-auth's standart code do the work. – altF4 Aug 19 '20 at 21:01
3

Same problem I faced. Here samesite flag is 'Lax' or 'strict' so cookie blocked by browser. Because cross-site response not set cookie.

So when in development you have to host your backend and frontend under same IP. ex. my backend :

python manage.py runserver localhost:8000

localhost:8000

frontend:

localhost:3000

Different ports same ip.

This is not the scenario when it goes to production you can have any domain. For more detail.

WithCredentials = true for both side..

Pradip Kachhadiya
  • 2,067
  • 10
  • 28
0

Well I was making a silly mistake, so moving {withCredentials:true} from here =>

export const login = (username, password) => dispatch => {
    //Headers
    const config = {
        headers: {
            "Content-type": "application/json"
        }
    }

    //Request body
    const body = JSON.stringify({ username, password })

    axios.post("http://127.0.0.1:8000/auth/login/", body, config, {withCredentials: true})
        .then(res => {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            })
        }).catch(err => {
            console.log(err)
            dispatch({
                type: LOGIN_FAIL
            })
        })
}

to here =>

    //Headers
    const config = {
        headers: {
            "Content-type": "application/json"
        },
        withCredentials: true
    }

solved my problem.

altF4
  • 269
  • 4
  • 19