2 docker containers (Django & React), isomorphic-fetch and a login request - django

My setup is running on Docker with a frontend (React) as well as a backend (Django) container.
I'm using the login-form component of the drf-react-app below in another project and am clueless as to how the api fetch request in the loginUser action creator (src/actions/user.js) knows which URL it is supposed to use..?
user.js:22 POST http://localhost:3000/api/obtain-auth-token/ 404 (Not Found)
I want it to send the request to the server at port 8000. I took the code from this drf-react boilerplate: https://github.com/moritz91/drf-react-login
export function loginUser(username, password) {
return (dispatch, getState) => {
const payload = {username, password};
dispatch({type: LOGIN_USER_REQUEST, payload});
return fetch(`/api/obtain-auth-token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(handleResponse(dispatch, LOGIN_USER_RESPONSE))
.then((json) => {
saveUser(json);
return json;
})
.catch(handleError(dispatch, LOGIN_USER_RESPONSE))
}
}
What am I missing?

In your package.json you have a proxy property set to "http://backend:8000". The proxy is used to redirect requests to a given url when you make a request against your local server http://localhost:3000. So if that's not working then you might be missing a step that enables the proxy.

Related

Django - why am i not authenticated after logging in from Axios/AJAX?

I'm building a separated VueJS/Django app where Django will communicate with the Vue frontend using JSON. In order to be able to use the standard session authentication and django-allauth i will deploy the two apps on the same server and on the same port.
Here is my problem: after i log in from the Vue app using Axios, i don't receive any response but i notice that a session is created on the db, so i'm assuming that i'm getting logged in. But if i try to reach and endpoint that prints request.user.is_authenticatedi get False, and request.user returns Anonymous, so i'm not logged in anymore. How can i solve this?
Here is my Axios code:
bodyFormData.append('login', 'root');
bodyFormData.append('password', 'test');
axios({
method: "post",
url: "http://127.0.0.1:8000/accounts/login/",
data: bodyFormData,
withCredentials: true,
headers: { "Content-Type": "application/json" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I think Django-Allauth supports AJAX authentication on its urls, but i don't understand how to make it return something and how can my Vue app stay authenticated once i submit the Axios form. Any advice is welcome!

Fetch Data from REST API sends two requests and can't authenticate

I'm trying to fetch data in my React app from an Django server with Django Rest Framework, I'm using the built in token authentication.
componentDidMount() {
let headers = {
"content-type": "application/json",
"authorization": "Token <token is here>"
};
fetch('http://localhost:8000/api/stats/', {
headers: headers,
})
.then(res => res.json())
.then((data) => {
this.setState({ games: data })
})
.catch(console.log)
}
Inspecting the page in Chrome reveals this
This looks like two separate requests but I'm not sure.
The requests that has status (failed) has the headers I provided in React with in it. This request seems to have failed completely, it did not even reach the server.
The other request that has the status 401 doesn't have the headers I provided. The request did however get a response from the server.
Anyone have an idea what's wrong?
Solved by David Nováks comment:
Installed django-cors-headers in my django project.
Added my React servers hosting address to CORS_ORIGIN_WHITELIST.

Nuxt.js and forwarding cookie to backend

I have site on nuxt.js (example.com) and backend on PHP (example.com/api/).
Some page get data from /api/some:
asyncData() {
return axios.get("http://example.com/api/some").then((response) => {
return response.data;
});
},
In PHP-handler of "/api/some" I write to the log recieved cookies.
If I go to some-page by link (browser ajax-request) cookies exist.
If I refresh page (server-side rendering) then cookies is empty.
Cookie reach to nuxt (context.req.headers.cookie is not empty) but don't transfer to backend.
How I can fix it?
Sorry, it work for axios.
const headers = {};
if (context.req) {
headers.Cookie = context.req.headers.coookie;
}
return axios({
url: url,
method: "get",
headers: headers,
}).then(/* ... */);

Sending x-csrf-token with axios request (Django/Reactjs)

I'm trying to send an x-csrf-token with an axios delete request to my django api. Here is the function:
export const deleteTripReport = (tripReport) => {
return dispatch => {
dispatch(deleteTripReportsPending());
axios.delete(`http://localhost:8000/api/v1/reports/${tripReport}`)
.then(response => {
dispatch(deleteTripReportsFulfilled());
})
.catch(err => {
dispatch(deleteTripReportsRejected(err));
})
}
}
I've tried adding
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
below my import. The django server returns 'Forbidden (CSRF Cookie not set'. I've tried adding headers
{headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': "mkTF7lcI4BVl42lJcFzqNbfeVvoVfLSH7e01kznsEQLYFEoWdchL0tuKZ5HeGnOa",
}}
with my actual cookie. Then the django server returns OPTIONS instead of DELETE, and the console logs missing 'x-csrf-token'.
I'm running the django server on port 8000 and the react server on 3000 for hot reloads, but I can run build, and both will run on 8000, but currently that is failing as well.

Fetch API with Cookie

I am trying out the new Fetch API but is having trouble with Cookies. Specifically, after a successful login, there is a Cookie header in future requests, but Fetch seems to ignore that headers, and all my requests made with Fetch is unauthorized.
Is it because Fetch is still not ready or Fetch does not work with Cookies?
I build my app with Webpack. I also use Fetch in React Native, which does not have the same issue.
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
In addition to #Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include' for the first /api/auth call too.
If you are reading this in 2019, credentials: "same-origin" is the default value.
fetch(url).then
Programmatically overwriting Cookie header in browser side won't work.
In fetch documentation, Note that some names are forbidden. is mentioned. And Cookie happens to be one of the forbidden header names, which cannot be modified programmatically. Take the following code for example:
Executed in the Chrome DevTools console of page https://httpbin.org/, Cookie: 'xxx=yyy' will be ignored, and the browser will always send the value of document.cookie as the cookie if there is one.
If executed on a different origin, no cookie is sent.
fetch('https://httpbin.org/cookies', {
headers: {
Cookie: 'xxx=yyy'
}
}).then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
P.S. You can create a sample cookie foo=bar by opening https://httpbin.org/cookies/set/foo/bar in the chrome browser.
See Forbidden header name for details.
Just adding to the correct answers here for .net webapi2 users.
If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.
// Access-Control-Allow-Origin
// https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
My issue was my cookie was set on a specific URL path (e.g., /auth), but I was fetching to a different path. I needed to set my cookie's path to /.
If it still doesn't work for you after fixing the credentials.
I also was using the :
credentials: "same-origin"
and it used to work, then it didn't anymore suddenly, after digging much I realized that I had change my website url to http://192.168.1.100 to test it in LAN, and that was the url which was being used to send the request, even though I was on http://localhost:3000.
So in conclusion, be sure that the domain of the page matches the domain of the fetch url.