Working with Next.js
and Django Rest Framework
, I'm authenticating users using JWT. First, when the user successfully logs in to the page, a cookie (which contains the JWT token) is sent to the browser. When the user tries to access a specific page, this cookie is used to validate the petition. I'm having trouble storing the cookie in the browser.
Django | login function
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def login(request):
...
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True, max_age=86400)
response.data ={
'message': 'success',
}
return response
And here is how I'm fetching /api/login
Next | Login.js
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
data.append('X-CSRFToken', csrftoken);
data.append('mode', 'same-origin');
data.append('Content-Type', 'application/json');
var config = {
method: 'post',
credentials: 'include', #I'm probably having issues with this
url: 'http://localhost:8000/api/login',
data : data
};
axios(config)
.then(res=> {
console.log('success'); #I got logged, but cookie is not stored
})
.catch(
error=>{this.setState({isError:true})}
);
Here is the set-cookie in the browser:
But JWT
is missing on storage:
As you can see, in both of them I'm receiving the cookie named JWT. But it's not being stored in the browser. Thank you in advance for your time and answers!
It's important to note is that mode
, credentials
aren't supported for configuring Axios
.It works in fetch api
because those options are part of the Request API
(docs for mode are here).
Axios uses a XMLHttpRequest under the hood, not Request.
Try this :
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
const headers = {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
}
var config = {
method: 'post',
withCredentials: true,
url: 'http://localhost:8000/api/login',
data : data,
{headers: headers}
};
axios(config)
.then(res=> {
console.log('success');
})
.catch(
error=>{this.setState({isError:true})}
);
------------------------------OR----------------------------------
put this at top:
axios.defaults.withCredentials = true
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
This Must in django:
settings.py:
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
'http://localhost:8000'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With