set-cookie returned in response headers, cors origin is not wildcarded, but cookie is not stored in browser - express

This question has been asked a million times, but I've tried it all and nothing seems to work.
My situation:
I've deployed a node/express backend as a Google Cloud Run service.
I am running my frontend locally, trying to login to my backend in the cloud. Frontend is served on http, backend on https. I have enabled cors on the backend. My config is:
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
}));
I am using axios, and I have set withCredentials: true:
axios.defaults.baseURL = ApiURL;
const { data } = await axios({
method: 'post',
url: `/api/login`,
data: {
username: this.state.username,
password: this.state.password,
keepLoggedIn: this.state.keepLoggedIn,
},
withCredentials: true,
});
This setup works perfectly when I run my backend locally, but of course there is no cors then. When I try to log in when the frontend is pointed at the Cloud Run service, I get a response from the backend with a set-cookie header as expected, but no cookie ever appears in the Storage > Cookies section of the Chrome dev console as it does with my local backend. There is then of course nothing sent with the rest of my axios requests, which need the cookie.
I've been at this for a full day and its driving me nuts. I'm sure there is something simple I'm missing. Any ideas?

Related

Browser fails to set cookies even with Set-Cookie response header

I am trying to get my Express backend to set a site-wide cookie on my NextJS frontend, each of which is running on separate virtual machines. The relevant backend and frontend configurations are:
In the frontend, I initate the following HTTP request:
fetch('http://192.168.1.<Express virtual machine>:3000/service', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({...}),
credentials: 'include'
}).then(res => res.json()).then(data => {console.log(data)});
In the backend, the following Express application is running with a global CORS middleware configured:
app.use(cors({origin: 'http://192.168.1.<Frontend virtual machine>:3000', credentials: true}));
app.post('/service', (req, res) => {
res.cookie('token', token, {
secure: false,
httpOnly: false,
sameSite: 'none'
});
res.json({...});
});
Upon initiating the HTTP request to /service, the Cookies section of my frontend application in the Storage (Firefox) or Application (Chrome) tab shows that there are no cookies set. However, in the network tab, the Cookies tab on my HTTP request shows that there is both a response cookie and a request cookie. The response cookie has path property set to '/' suggesting that it should have been set site-wide.

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

Axios not sending custom header during options request

I have a running Vue.js application that request to the server.
My client-side application is running on e.g. cms.abc.com and the server in ApiGee running on this dns server.abc.com
The request code using axios is
const headers = {
'x-api-key': 'xxxxx123123'
}
return axios({
method: get,
url: 'server.abc.com/items',
headers: headers
}).then(response => {
console.log(respnose.data)
})
When I check the browser network I'm getting status 401 Unauthorized during OPTIONS request.
The APIgee CORS has been enabled, but when I check the logs from the ApiGee the value for x-api-key is missing.
I'm also not sure why my client side application is still sending OPTIONS request. I'm expecting that it should skip the CORS since the client and the server are having the same origin. which is abc.com

CORS issue with Express Server API to Next.js

I have a user authentication server setup using Express and Node.js in my localhost Port 3333 and I am trying to connect to the endpoint in Next.js port 3000 using isomorphic-unfetch for the fetch. I am getting a CORS 401 error, I have done a fair bit of research already but just wanted to know whether it was possible connecting to a Express server on localhosts? I have tried adding "Access-Control-Allow-Origin": "*", "Content-Type": "multipart/form-data" to a header object. The express server has cors setup already.
This function below is called on click of a button.
onLoginClick = async () => {
let header = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
});
const res = await fetch("http://localhost:3333", {
method: "POST",
header,
body: JSON.stringify({
username: "USER",
password: "PASSWORD"
})
});
}
Error message -
http://localhost:3333/ 401 (Unauthorized)
Response {type: "cors", url: "http://localhost:3333/", redirected: false, status: 401, ok: false, …}
First of all, CORS is configured on the server side. You configure your server to allow calls from specific origins.
In your code, onLoginClick is a client-side code, it runs on the browser, client cannot decide which origin the server should allowed to, that would defeat the purpose of having CORS.
Usually you don't need to change the cors configuration in a Next.js app, because you would be calling the API from the same origin that hosted the client side app.
By default, Next.js only support same-origin for API Routes, if you need to customize it, you can use micro-cors.

Why is XHR request pending forever on live server?

So i have a react app which if someone is logged in will check for it's account level and based on that will enable or disable features. It worked until it was all localhost, but now i have a server in the cloud and the request is pending forever. Other requests to the same endpoint works fine. I tried changing the address to localhost, but then it looks for the API server on my PC. It's strange because the same endpoint works with other requests. This single request also works on localhost but not if i use server's IP. Here's an image of the Network page of Chrome development tools: https://i.ibb.co/c2r8Js1/Screenshot-at-2019-12-27-15-11-41.png
getLoggedLevel = () => {
var URL = process.env.REACT_APP_API_URL;
var URL2 = 'http://localhost:8000/requests'
axios({
url: URL,
method: 'post',
data: {
message: 'getLoggedLevel',
username: JSON.parse(localStorage.getItem('loggedUser')).username
}
}).then(res => {
this.setState({loggedLevel: res.data.level})
})
}
Edit: I created a separate endpoint for that single request, and it's 404 however in firefox it's 200 for OPTIONS... Now i'm really confused :(