Node Express JS Cookies to Client - reactjs

i have an express app. Im trying to set cookies to client server address by doing so:
const token = jwt.sign({ userName: userName, id: user.id }, 'secret');
console.log(token);
res.cookie('user', token, { httpOnly: false, secure: false });
res.status(200).send({
success: true,
message: 'Authorized',
user: user,
});
I have tried adding multiple options to res.cookie but doesnt work.
My goal is to set cookies with token to client address but it sets to server address.

Related

chrome or express or react not allowing cookie to be set in browser

apologies in advance for what seems like a repeat question.
I've tried lots of other stack overflow and other solutions and cant seem to see what I'm doing wrong.
I'm trying to send and set a cookie from my express server to my front end so that it can be sent back with each request to authenticate.
This is working in insomnia and on the 9090 host but when I push it up to the proper server it just stops working and wont set the cookie at all.
all the headers are showing up
I'm also getting no errors in the console so no help there.
react example of request
export const logIn = (formInput) => {
return listApi.post(`/users/authenticate`, formInput, {withCredentials:true})
.then( ({ data }) => {
return data
})
express
app.use(cors({
origin: "http://192.xxx.x.xx:xxxx",
credentials: true,
origin: true
}));
res.status(200)
.header('Access-Control-Allow-Credentials', true)
.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.header("Access-Control-Allow-Origin", "http://192.168.1.69:3000")
.header("Access-Control-Allow-Methods", "GET,POST,PATCH,PUT,DELETE,OPTIONS")
.cookie('access_token', token, {expires:tokenExpire,
sameSite: 'None',
secure: true,
httpOnly: true,
Domain: 'http://192.168.1.69:3000'})
.send({ msg: 'success' });
} else {
Promise.reject( {status: 401, msg: 'unauthorized - invalid username and password'})
.catch(err => next(err))
}
};
EDIT:
here are the things I've read so far
res.cookie not setting cookie in browser
Express-Session not working in production/deployment
Express-session cookie not saving in browser
Cookies on localhost with explicit domain
https://www.reddit.com/r/reactjs/comments/vxvdib/cookie_not_being_set_in_react_app_express_backend/
Express doesn't set a cookie

TypeError: Cannot read properties of undefined (reading '0') error

I'm starting the app and getting this error:
email: req.user.emails[0].value,
^ TypeError: Cannot read properties of undefined (reading '0')
It was working good until I added the same code but for facebook login, it was reading and storing but I don't why it stopped.
The code:
router.get("/googleLogin/success", async (req, res)=>{
if(req.user){
const user = await User.findOne({provider_id: req.user.id,
provider: req.user.provider})
if(user){
res.status(200).json({
success: true,
message: "success",
user: user
})
console.log("GOOGLE USER IS: " + user)
}else{
const checkUserEmail = await User.findOne({email: req.user.email})
if(checkUserEmail){
res.status(401).json({
success: false,
message: "User already Exist with this email id",
})
}else{
const user = await User.create({
username: req.user.name.givenName+ "_" +req.user.name.familyName,
firstName: req.user.name.givenName,
lastName: req.user.name.familyName,
// THE ERROR IS HERE
email: req.user.emails[0].value,
provider: req.user.provider,
provider_id: req.user.id,
profilePic: req.user.photos[0].value,
});
res.status(200).json({
success: true,
message: "success",
user: user
})
}
}
console.log("CURRNT USER: ", user);
}
})
Basically the req.user.emails is undefined.
You are likely missing the email scope in profileFields option.
passport.use(new FacebookStrategy({
clientID: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
callbackURL: "http://www.example.com/auth/facebook/callback",
passReqToCallback: true,
profileFields: ['id', 'emails', 'name'] // emails needs to be listed here
}))
and
app.get('/connect/facebook', passport.authorize('facebook', {
scope : ['email'], // list email here
}));
See Passport-Facebook authentication is not providing email for all Facebook accounts
kindly ensure you are writing the code for the Facebook strategy separately from the Google strategy and also check to see if you are not mixing up the two endpoints
for example:
router.get("/googleLogin/success", async (req, res)=>{}
should be called when using the google strategy and
router.get("/facebookLogin/success", async (req, res)=>{}
should be called when using the Facebook strategy.
also have it in mind that the endpoint in your callbackURL should be the same endpoint you call i.e if:
callbackURL: "http://localhost:3000/facebookLogin/success"
then the endpoint to call would be:
/facebookLogin/success
if you still get the same error kindly post both the Facebook Strategy code and the Google Strategy code for a clear comparison

Cookies are being sent but chrome doesn't set them

I saw many similar questions and played with many combinations but nothing works.
I specify that it's all on localhost.
regUser = () => {
var username = getE("username-input").value;
var email = getE("email-input").value;
var password = getE("password-input").value;
axios({
url: process.env.REACT_APP_API_URL + "register",
method: "post",
data: {
username, email, password
},
withCredentials: true
}).then(res => {
if(res.data.regSuccess) {
// Registration successful
this.setState({
regSuccess: true,
regTextHidden: false,
regText: "Registration Successful! An e-mail was sent to the specified e-mail address with confirmation information! You will be redirected to the Login page..."
}, ()=>{
setTimeout(
()=>{window.location.href=("/login")}, 5000
)
})
} else {
this.setState({
regSuccess: false,
regTextHidden: false,
regText: "An error occured. Please try again later!"
})
}
})
}
Backend code:
f.checkPassword(userData, function(result) {
if(!result.correct) {
// Wrong password
res.send({found: true, correct: false})
} else {
// Proceed with authentication
var token = f.genToken(userData.user);
res.header("OPTIONS", 'true')
res.cookie("access-token", token.token, {httpOnly: true, sameSite: "none", maxAge: "100000", secure: false});
res.send({found: true, correct: true})
}
})
No matter what cookie settings I use, they are being sent, the "Set-Cookie" header is present but no cookie is set.
I've played with every option for like 2 days but it just doesn't work. Any advice?
I was stuck on this for a while too. A couple things fixed it for me:
in the frontend in the axios call (which I see you've done), use:
withCredentials: true
Then in the backend in express, use npm package cors, with the following:
const app = express();
app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));
Or use whatever your url origin is. Hope this works for you.

Working with express session and angularjs

I have a problem trying to create an APIRest with express.
Currently, I have register and login working correctly using MongoDB and passport, the problem is that when I login, I need the API to understand that the user is still logged in, so I'm using:
//Session
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { httpOnly: false, maxAge: null, secure: false },
store: new MongoStore({
url: configDB.url,
collection: 'sessions'
})
}));
To check if the user is authenticated, i'm using:
//Confirm Login status
app.get('/api/loggedin', function (req, res) {
return res.send(req.isAuthenticated() ? req.user : 'Not Logged!');
});
With the function:
function IsAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
next(res.send('Sorry!'));
}
}
Using Postman, it works just fine, I can see te cookie "connect.sid". But when I login from angularjs using this endpoint, the cookie is not beeing set, and basically, it does not work, returns "Not Logged!".
PS: I'm using ionic as my framework. My node API server is under Azure webapp.
Any question lt me know guys, thanks so far!

passportjs and backbone: authenticating users

Currently I been using a chrome app called Postman to test my services from nodejs/express/passportjs.
Currently I'm having trouble wrapping my head around how I should grab the user info and authenticate it with backbone.
I would try to authenticate the user like so:
$.post("http://localhost:3000/login", { username: "joe", password: "pass" })
.done(function(data) {
console.log(data)
//try to pull a service that's protected by passport
})
.fail(function(data) {
console.log(data)
})
Which is not working at all when it's successful. Its giving the 500 error I set for when someone isn't logged in.
Any particular direction I should be going in to manage authentication with passportjs in backbone?
The 500 error means some part of the code in the server is not working properly.
You can send the logged in user from express using passport. You can follow the following example.
var app = express();
var login = require('./routes/login');
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true }),
login.login);
where your login.js file may look like this
exports.login = function (req, res) {
res.json(req.user);
}
the authenticate process of passport populates user variable in request (req) with the logged in user.
Please note, you have to use cookie parser and session of express to make the passport session working. e.g.,
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));
your local authentication may look like the following (say you have a function that finds user by username (findByUsername)).
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
});
}
));

Resources