I have a Koa and GraphQL API with an authentication resolver which adds sets an auth token to the response cookies.
My API runs on http://localhost:3000 and my front end runs on http://localhost:3001. In order to make this work, I needed to add withCredentials flag to my API request as well as configure my Koa/Cors options with { origin: false, credentials: true }. Without these settings I would get a CORS error which I find confusing because they are both on localhost so technically the same domain...?
There will be multiple front ends using this API and will need to authenticate and get the auth token set in the cookie. When I spoof my domain name as http://app1.dev & http://app2.dev, both calling the API on http://localhost:3000, the auth token gets set in the response cookies but the browser does not store the cookie like it did when everything was localhost.
On my API, I am using #koa/cors for my configuring my cors and then set the following:
app.use(cors({ origin: false, credentials: true }))
On my front end react app, I have a request function which I use for all my GraphQL queries:
const request = query => {
const request = axios.create({
baseURL: apiUrl,
headers: {'X-apikey': apiKey},
withCredentials: true,
});
return request.post('/graphql', { query })
.then(res => res.data)
.catch(console.error)
}
Why are the cookies not getting set in the browser?
EDIT: Updated my axios request to create instance of axios and attempting to set withCredentials. I am still not seeing the credentials param in my request in dev tools though. I suspect this could be the issue?
I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:
SubmitClick(){
//console.log('load Get User page'); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'deadpool#gmail.com',
first_name: 'Wade',
last_name: 'Wilson',
personal_phone: '(11) 91111-2222',
password: 'wolv3Rine'
})
})
//this.props.history.push('/get'); //change page layout and URL
}
and I get the following message on my browser:
OPTIONS http://localhost:4000/users/ 401 (Unauthorized)
Failed to load http://localhost:4000/users/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.
I'm using Google Chrome as my default browser.
My backend code is the following:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var basicAuth = require('express-basic-auth')
const app = express();
mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl'
}
}))
app.use(bodyParser.json());
app.use(function(err, req, res, next){
console.log(err);
//res.status(450).send({err: err.message})
});
app.use(require('./routes/api'));
app.listen(4000, function(){
console.log('Now listening for request at port 4000');
});
It may not be the same problem as the OP, but I was able to get basic auth protected fetches working just by adding a credentials mode...
fetch(
'http://example.com/api/endpoint',
{ credentials: "same-origin" }
)
See here: https://github.github.io/fetch/ under Request > Options
You're trying to access port 4000 (your API, or backend) from port 3000 (Your client). This violates the Same-origin policy, even though you're clearly running both the client and the API from the same machine.
To get around this the easiest way is to just fire up your client from the same port as your API (port 4000) this should allow your host to see that you're trying to access resources from the same domain/port which won't force a preflight request.
If that's not possible you'll have to configure CORS for your API, and this question doesn't give any details about the backend so I can't instruct you on how to do that at the moment.
And of course this approach obviously won't work if you're running two separate servers in production, but that's probably outside of the scope of this question.
I am sending requests from the client to my Express.js server using Axios.
I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.
This is my clientside request example:
axios.get(`some api url`).then(response => ...
I tried to access headers or cookies by using these properties in my Express.js server:
req.headers
req.cookies
Neither of them contained any cookies. I am using cookie parser middleware:
app.use(cookieParser())
How do I make Axios send cookies in requests automatically?
Edit:
I set cookie on the client like this:
import cookieClient from 'react-cookie'
...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
axios.get('path/to/my/cookie/api').then(response => {
if(response.status == 200){
cookieClient.save('cookie-name', response.data, {path:'/'})
}
})
}
...
While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.
You can use withCredentials property.
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.
axios.get(BASE_URL + '/todos', { withCredentials: true });
Also its possible to force credentials to every Axios requests
axios.defaults.withCredentials = true
Or using credentials for some of the Axios requests as the following code
const instance = axios.create({
withCredentials: true,
baseURL: BASE_URL
})
instance.get('/todos')
TL;DR:
{ withCredentials: true } or axios.defaults.withCredentials = true
From the axios documentation
withCredentials: false, // default
withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials
If you pass { withCredentials: true } with your request it should work.
A better way would be setting withCredentials as true in axios.defaults
axios.defaults.withCredentials = true
It's also important to set the necessary headers in the express response. These are those which worked for me:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', yourExactHostname);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
I am not familiar with Axios, but as far as I know in javascript and ajax there is an option
withCredentials: true
This will automatically send the cookie to the client-side. As an example, this scenario is also generated with passportjs, which sets a cookie on the server
So I had this exact same issue and lost about 6 hours of my life searching, I had the
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
You can use withCredentials property to pass cookies in the request.
axios.get(`api_url`, { withCredentials: true })
By setting { withCredentials: true } you may encounter cross origin issue. To solve that
you need to use
expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));
Here you can read about withCredentials
What worked for me:
Client Side:
import axios from 'axios';
const url = 'http://127.0.0.1:5000/api/v1';
export default {
login(credentials) {
return axios
.post(`${url}/users/login/`, credentials, {
withCredentials: true,
credentials: 'include',
})
.then((response) => response.data);
},
};
Note: Credentials will be the body of the post request, in this case the user login information (Normally obtained from the login form):
{
"email": "user#email.com",
"password": "userpassword"
}
Server Side:
const express = require('express');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 5000;
app.use(
cors({
origin: [`http://localhost:${port}`, `https://localhost:${port}`],
credentials: 'true',
})
);
Fatih's answer is still valid and great in 2022.
Also axios.defaults.withCredentials = true will do the trick.
It seems passing { withCredentials: true } to individual axios calls is deprecated.
How do I make Axios send cookies in requests automatically?
set axios.defaults.withCredentials = true;
or for some specific request you can use axios.get(url,{withCredentials:true})
this will give CORS error if your 'Access-Control-Allow-Origin' is set to
wildcard(*).
Therefore make sure to specify the url of origin of your request
for ex: if your front-end which makes the request runs on localhost:3000 , then set the response header as
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
also set
res.setHeader('Access-Control-Allow-Credentials',true);
for people still not able to solve it, this answer helped me.
stackoverflow answer: 34558264
TLDR;
one needs to set {withCredentials: true} in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.
Another solution is to use this library:
https://github.com/3846masa/axios-cookiejar-support
which integrates "Tough Cookie" support in to Axios. Note that this approach still requires the withCredentials flag.
After trying for 2 days long and after trying out from the suggestions here this is what worked for me.
express:
cors: cors({ origin: "http:127.0.0.1:3000", credentials: true, })
Cookie : Make sure your cookie has secure: true, sameSite: "None"
Frontend(React)
axios.defaults.withCredentials = true;
(withCredentials : true did not work for me) to the places where you request the cookie as well as to the place where you send the cookie (GET/POST)
Hope this helps others as well.
You are getting the two thinks mixed.
You have "react-cookie" and "axios"
react-cookie => is for handling the cookie on the client side
axios => is for sending ajax requests to the server
With that info, if you want the cookies from the client side to be communicated in the backend side as well, you will need to connect them together.
Note from "react-cookie" Readme:
Isomorphic cookies!
To be able to access user cookies while doing server-rendering, you
can use plugToRequest or setRawCookie.
link to readme
If this is what you need, great.
If not, please comment so I could elaborate more.
For anyone where none of these solutions are working, make sure that your request origin equals your request target, see this github issue.
I short, if you visit your website on 127.0.0.1:8000, then make sure that the requests you send are targeting your server on 127.0.0.1:8001 and not localhost:8001, although it might be the same target theoretically.
This worked for me:
First, I had to make a new instance of axios with a custom config
Then, I used that axios instance to make a post request
See code below:
const ax = axios.create({
baseURL: 'yourbaseUrl',
withCredentials: true,
});
const loginUser = () => { const body ={username:state.values.email, password:state.values.password};
ax.post('/login',body).then(function(response){
return response}).then().catch(error => console.log(error));}
source:
https://www.npmjs.com/package/axios#creating-an-instance
This won't apply to everyone, but I was using a React frontend with Vite and it was serving the localhost as 127.0.0.1:5173, which is what I put as the CORS allowable domain. As soon as I both to localhost everything worked as expected!
// use this while creating axios instance
const API = axios.create({
baseURL: "http://localhost:4000", // API URL
withCredentials: true,
});
// USE THIS MIDDLEWARE in app.js of backend
first, install cors npm i cors
var cors = require("cors"); // This should be at the end of all middlewares
const corsOptions = {
origin: "http://localhost:3000",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
In my case, the problem was with the cookie, not with Axios; although I was receiving and sending the cookie from / to the same domain / subdomain / host, I was expecting it to work with different resources in different paths - but my coookie was acting like I had set it to a single Path, even though I omitted that attribute. Explicitly setting Path=/; in the cookie solved the issue.
Set the proxy in package.json(Frontend) and restart the server again (problem solved)
I am working on express js and in the incoming POST request, the username and password are present in the body of the request, I want to implement routing such that an authorisation header can be added to the incoming req object
My routing is as follows :
router.route('/token')
.post(function(req,res,next){
if(req.body.client_id){
//set headers for authentication, e.g "Authorization":"Basic dskvnksnsnjsnvsnlvnsd"
next();
}
},authController.isClientAuthenticated,oauth2Controller.token);
You can add headers by using the req.headers property:
req.headers.authorization = 'Basic ...'
Note that there is a res.headersSent property, which can be used to determine if headers have already been sent to the client, otherwise you will encounter an error.
I am using oauth2 (node.js and the connect-oauth library) to connect to the google contacts API version 3.0.
Doing so, I get a response such as:
{ access_token : "...",
"token_typen": "Bearer",
"expires_in" : 3600,
"id_token": "..." }
I am missing the refresh token used to get a new access token as soon as the latter is expired.
options for oauth2
{ host: 'accounts.google.com',
port: 443,
path: '/o/oauth2/token',
method: 'POST',
headers:
{ 'Content-Type': 'application/x-www-form-urlencoded',
Host: 'accounts.google.com',
'Content-Length': 247 } }
post-body
'redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&grant_type=authorization_code&client_id=CLIENTID&client_secret=CLIENTSECRET&type=web_server&code=4%2F3gbiESZTEOjiyFPLUhKfE_a_jr8Q'
NOTE: I tried to add approval_prompt=force from a similar question to the request-post_body but this resulted in an Error
{ statusCode: 400, data: '{\n "error" : "invalid_request"\n}' }
NOTE: I tried to add approval_prompt=force from a similar question to the request-post_body but this resulted in an Error
You don't need the approval_prompt param when you ask for a token. The *approval_prompt* param is for the authorization part.
I am missing the refresh token...
The only way you DON'T get a *refresh_token* is when:
use the Client-side Applications flow;
include the access_type=online param in the authorization code request.
So, try adding: access_type=offline, to the authorization code request.
Edit:
i.e.:
https://accounts.google.com/o/oauth2/auth?client_id=**your_client_id**&scope=https://www.googleapis.com/auth/plus.me&redirect_uri=http://localhost&response_type=code&access_type=offline
If you're getting 400 is because you are adding an invalid parameter or missing one.
Good luck!
One time I did this was testing - I had deleted the google authorisation token from the app - so it tried to get another one and it did but without a refresh token.
So check the app you are testing is not authorised for the account you are testing from (does that make sense?)