Related
I try to use nodemailer to implement a contact form using NodeJS but it works only on local it doesn't work on a remote server...
My error message :
[website.fr-11 (out) 2013-11-09T15:40:26] { [AuthError: Invalid login - 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787
[website.fr-11 (out) 2013-11-09T15:40:26] 534 5.7.14 54 fr4sm15630311wib.0 - gsmtp]
[website.fr-11 (out) 2013-11-09T15:40:26] name: 'AuthError',
[website.fr-11 (out) 2013-11-09T15:40:26] data: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX\r\n534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC\r\n534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX\r\n534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r\r\n534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.\r\n534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\r\n534 5.7.14 54 fr4sm15630311wib.0 - gsmtp',
[website.fr-11 (out) 2013-11-09T15:40:26] stage: 'auth' }
My controller :
exports.contact = function(req, res){
var name = req.body.name;
var from = req.body.from;
var message = req.body.message;
var to = '*******#gmail.com';
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "******#gmail.com",
pass: "*****"
}
});
var mailOptions = {
from: from,
to: to,
subject: name+' | new message !',
text: message
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
res.redirect('/');
}
});
}
I solved this by going to the following url (while connected to google with the account I want to send mail from):
https://www.google.com/settings/security/lesssecureapps
There I enabled less secure apps.
Done
See nodemailer's official guide to connecting Gmail:
https://community.nodemailer.com/using-gmail/
-
It works for me after doing this:
Enable less secure apps - https://www.google.com/settings/security/lesssecureapps
Disable Captcha temporarily so you can connect the new device/server - https://accounts.google.com/b/0/displayunlockcaptcha
Easy Solution:
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'somerealemail#gmail.com',
pass: 'realpasswordforaboveaccount'
}
}));
var mailOptions = {
from: 'somerealemail#gmail.com',
to: 'friendsgmailacc#gmail.com',
subject: 'Sending Email using Node.js[nodemailer]',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Step 1:
go here https://myaccount.google.com/lesssecureapps and enable for less secure apps. If this does not work then
Step 2
go here https://accounts.google.com/DisplayUnlockCaptcha and enable/continue and then try.
for me step 1 alone didn't work so i had to go to step 2.
i also tried removing the nodemailer-smtp-transport package and to my surprise it works. but then when i restarted my system it gave me same error, so i had to go and turn on the less secure app (i disabled it after my work).
then for fun i just tried it with off(less secure app) and vola it worked again!
You should use an XOAuth2 token to connect to Gmail. No worries, Nodemailer already knows about that:
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
XOAuth2: {
user: smtpConfig.user,
clientId: smtpConfig.client_id,
clientSecret: smtpConfig.client_secret,
refreshToken: smtpConfig.refresh_token,
accessToken: smtpConfig.access_token,
timeout: smtpConfig.access_timeout - Date.now()
}
}
};
You'll need to go to the Google Cloud Console to register your app. Then you need to retrieve access tokens for the accounts you wish to use. You can use passportjs for that.
Here's how it looks in my code:
var passport = require('passport'),
GoogleStrategy = require('./google_oauth2'),
config = require('../config');
passport.use('google-imap', new GoogleStrategy({
clientID: config('google.api.client_id'),
clientSecret: config('google.api.client_secret')
}, function (accessToken, refreshToken, profile, done) {
console.log(accessToken, refreshToken, profile);
done(null, {
access_token: accessToken,
refresh_token: refreshToken,
profile: profile
});
}));
exports.mount = function (app) {
app.get('/add-imap/:address?', function (req, res, next) {
passport.authorize('google-imap', {
scope: [
'https://mail.google.com/',
'https://www.googleapis.com/auth/userinfo.email'
],
callbackURL: config('web.vhost') + '/add-imap',
accessType: 'offline',
approvalPrompt: 'force',
loginHint: req.params.address
})(req, res, function () {
res.send(req.user);
});
});
};
Worked fine:
1- install nodemailer, package if not installed
(type in cmd) : npm install nodemailer
2- go to https://myaccount.google.com/lesssecureapps and turn on Allow less secure apps.
3- write code:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'trueUsername#gmail.com',
pass: 'truePassword'
}
});
const mailOptions = {
from: 'any#any.com', // sender address
to: 'true#true.com', // list of receivers
subject: 'test mail', // Subject line
html: '<h1>this is a test mail.</h1>'// plain text body
};
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
})
4- enjoy!
I had the same problem. Allowing "less secure apps" in my Google security settings made it work!
Non of the above solutions worked for me. I used the code that exists in the documentation of NodeMailer. It looks like this:
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: 'user#example.com',
serviceClient: '113600000000000000000',
privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...',
accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
expires: 1484314697598
}
});
Same problem happened to me too. I tested my system on localhost then deployed to the server (which is located at different country) then when I try the system on production server I saw this error. I tried these to fix it:
https://www.google.com/settings/security/lesssecureapps Enabled it but it was not my solution
https://g.co/allowaccess I allowed access from outside for a limited time and this solved my problem.
I found the simplest method, described in this article mentioned in Greg T's answer, was to create an App Password which is available after turning on 2FA for the account.
myaccount.google.com > Sign-in & security > Signing in to Google > App Passwords
This gives you an alternative password for the account, then you just configure nodemailer as a normal SMTP service.
var smtpTransport = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: "username#gmail.com",
pass: "app password"
}
});
While Google recommend Oauth2 as the best option, this method is easy and hasn't been mentioned in this question yet.
Extra tip: I also found you can add your app name to the "from" address and GMail does not replace it with just the account email like it does if you try to use another address. ie.
from: 'My Pro App Name <username#gmail.com>'
It is resolved using nodemailer-smtp-transport module inside createTransport.
var smtpTransport = require('nodemailer-smtp-transport');
var transport = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '*******#gmail.com',
pass: '*****password'
}
}));
Many answers advice to allow less secure apps which is honestly not a clean solution.
Instead you should generate an app password dedicated to this use:
Log in to your Google account
Go to security
Under Signing in to Google enable 2-Step Verification
Under Signing in to Google click on App passwords.
You'll now generate a new password. Select the app as Mail and the device as Other (Custom name) and name it.
Save the app password
You can now use this app password instead of your log in password.
Try disabling captchas in your gmail account; probably being triggered based on IP address of requestor.
See: How to use GMail as a free SMTP server and overcome captcha
For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)
I hope will help someone.
var sendEmail = function(somedata){
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL,
// you can try with TLS, but port is then 587
auth: {
user: '***#gmail.com', // Your email id
pass: '****' // Your password
}
};
var transporter = nodemailer.createTransport(smtpConfig);
// replace hardcoded options with data passed (somedata)
var mailOptions = {
from: 'xxxx#gmail.com', // sender address
to: 'yyyy#gmail.com', // list of receivers
subject: 'Test email', // Subject line
text: 'this is some text', //, // plaintext body
html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return false;
}else{
console.log('Message sent: ' + info.response);
return true;
};
});
}
exports.contact = function(req, res){
// call sendEmail function and do something with it
sendEmail(somedata);
}
all the config are listed here (including examples)
If you use Express, express-mailerwrapsnodemailervery nicely and is very easy to use:
//# config/mailer.js
module.exports = function(app) {
if (!app.mailer) {
var mailer = require('express-mailer');
console.log('[MAIL] Mailer using user ' + app.config.mail.auth.user);
return mailer.extend(app, {
from: app.config.mail.auth.user,
host: 'smtp.gmail.com',
secureConnection: true,
port: 465,
transportMethod: 'SMTP',
auth: {
user: app.config.mail.auth.user,
pass: app.config.mail.auth.pass
}
});
}
};
//# some.js
require('./config/mailer.js)(app);
app.mailer.send("path/to/express/views/some_view", {
to: ctx.email,
subject: ctx.subject,
context: ctx
}, function(err) {
if (err) {
console.error("[MAIL] Email failed", err);
return;
}
console.log("[MAIL] Email sent");
});
//#some_view.ejs
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><%= subject %></title>
</head>
<body>
...
</body>
</html>
For some reason, just allowing less secure app config did not work for me even the captcha thing. I had to do another step which is enabling IMAP config:
From google's help page: https://support.google.com/mail/answer/7126229?p=WebLoginRequired&visit_id=1-636691283281086184-1917832285&rd=3#cantsignin
In the top right, click Settings Settings.
Click Settings.
Click the Forwarding and POP/IMAP tab.
In the "IMAP Access" section, select
Enable IMAP.
Click Save Changes.
all your code is okay only the things left is just go to the link https://myaccount.google.com/security
and keep scroll down and you will found Allow less secure apps: ON and keep ON, you will find no error.
Just add "host" it will work .
host: 'smtp.gmail.com'
Then enable "lesssecureapps" by clicking bellow link
https://myaccount.google.com/lesssecureapps
Google has disabled the Less Secure App Access, Below is New Process to use Gmail in Nodejs
Now you have to enable 2 Step Verification in Google (How to Enable 2 Step Auth)
You need to generate App Specific Password. Goto Google My Account > Security
Click on App Password > Select Other and you will get App Password
You can use normal smtp with email and App password.
exports.mailSend = (res, fileName, object1, object2, to, subject, callback)=> {
var smtpTransport = nodemailer.createTransport('SMTP',{ //smtpTransport
host: 'hostname,
port: 1234,
secureConnection: false,
// tls: {
// ciphers:'SSLv3'
// },
auth: {
user: 'username',
pass: 'password'
}
});
res.render(fileName, {
info1: object1,
info2: object2
}, function (err, HTML) {
smtpTransport.sendMail({
from: "mail#from.com",
to: to,
subject: subject,
html: HTML
}
, function (err, responseStatus) {
if(responseStatus)
console.log("checking dta", responseStatus.message);
callback(err, responseStatus)
});
});
}
You must add secureConnection type in you code.
I was using an old version of nodemailer 0.4.1 and had this issue. I updated to 0.5.15 and everything is working fine now.
Edited package.json to reflect changes then
npm install
Just attend those:
1- Gmail authentication for allow low level emails does not accept before you restart your client browser
2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like below
const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
routes.get('/test', (req, res) => {
res.status(200).json({ message: 'test!' });
});
routes.post('/Email', (req, res) =>{
var smtpTransport = nodemailer.createTransport({
host: "smtp.gmail.com",
secureConnection: false,
port: 587,
requiresAuth: true,
domains: ["gmail.com", "googlemail.com"],
auth: {
user: "your gmail account",
pass: "your password*"
}
});
var mailOptions = {
from: 'from#gmail.com',
to:'to#gmail.com',
subject: req.body.subject,
//text: req.body.content,
html: '<p>'+req.body.content+' </p>'
};
smtpTransport.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log('Error while sending mail: ' + error);
} else {
console.log('Message sent: %s', info.messageId);
}
smtpTransport.close();
});
})
module.exports = routes;
first install nodemailer
npm install nodemailer --save
import in to js file
const nodemailer = require("nodemailer");
const smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "example#gmail.com",
pass: "password"
},
tls: {
rejectUnauthorized: false
}
});
const mailOptions = {
from: "example#gmail.com",
to: sending#gmail.com,
subject: "Welcome to ",
text: 'hai send from me'.
};
smtpTransport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
}
else {
console.log("mail sent");
}
});
working in my application
You may need to "Allow Less Secure Apps" in your Gmail account (it's all the way at the bottom). You also may need to "Allow access to your Google account".
You also may need to "Allow access to your Google account".
This is my Nodemailer configuration which worked after some research.
Step 1: Enable lesssecureapp
https://www.google.com/settings/security/lesssecureapps
Step 2: The Nodemailer configuration for Gmail
Setting up the transporter : A transporter is going to be an object that can send mail. It is the transport configuration object, connection URL, or a transport
plugin instance
let transporter = nodemailer.createTransport({
service: 'gmail', // the service used
auth: {
user: process.env.EMAIL_FROM, // authentication details of sender, here the details are coming from .env file
pass: process.env.EMAIL_FROM_PASSWORD,
},
});
Writing the message
const message = {
from: 'myemail#gmail.com', // sender email address
to: "receiver#example.com, receiver2#gmail.com", // reciever email address
subject: `The subject goes here`,
html: `The body of the email goes here in HTML`,
attachments: [
{
filename: `${name}.pdf`,
path: path.join(__dirname, `../../src/assets/books/${name}.pdf`),
contentType: 'application/pdf',
},
],
Sending the mail
transporter.sendMail(message, function (err, info) {
if (err) { // if error
console.log(err);
} else {
console.log(info); // if success
}
});
I also had issues with nodemailer email sending when running on Vercel lambda in production.
What fixed it in my case was to await for sendMail Promise to resolve.
I also added nodemailer-smtp-transport like suggested in this thread but I don't think it made a difference.
Here is my whole function:
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '***#gmail.com',
pass: process.env.SMTP_PASSWORD,
},
}));
async function contact(req: any, res: any) {
try {
const response = await transporter.sendMail({
from: '"*** <***gmail.com>', // sender address
to: "***#gmail.com", // list of receivers
subject: `***`, // Subject line
html: `${req.body.message}<br/><br/>${req.body.firstname} ${req.body.lastname} - <b>${req.body.email}</b>`, // html body
});
} catch (error: any) {
console.log(error);
return res.status(error.statusCode || 500).json({ error: error.message });
}
return res.status(200).json({ error: "" });
}
export default contact;
As pointed out by Yaach, as of May 30th, 2022, Google no longer supports Less Secure Apps, and instead switched over to their own Gmail API.
Here is the sample code for Gmail SMTP with nodemailer.
"use strict";
const nodemailer = require("nodemailer");
async function main() {
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
transportMethod: "SMTP",
secureConnection: true,
port: 465,
secure: true, // upgrade later with STARTTLS
auth: {
user: "yourEmail#gmail.com",
pass: "Your App Specific password",
},
});
let info = await transporter.sendMail(
{
from: "yourEmail#gmail.com",
to: "to#gmail.com",
subject: "Testing Message Message",
text: "I hope this message gets delivered!",
html: "<b>Hello world?</b>", // html body
},
(err, info) => {
if (err) {
console.log(err);
} else {
console.log(info.envelope);
console.log(info.messageId);
}
}
);
}
main();
Less secure option is not supported anymore by gmail.
For sending email from third party, gmail is also not allowing with its user password.
You should now use App Password to resolve this issue.
Hope this link will help to set your app password.
https://support.google.com/mail/answer/185833?hl=en
There is another option to use SendGrid for email delivery with no failure. A lot of the time, Nodemailer gives failure for mail which could happen frequently.
Nodemailer can be found in the link.
I have an api in express js that stores token in cookie on the client-side (react). The cookie is generated only when the user logins into the site. For example, when I test the login api with the postman, the cookie is generated as expected like this:
But when I log in with react.js then no cookie is found in the browser. Looks like the cookie was not passed to the front end as the screenshot demonstrates below:
As we got an alert message this means express api is working perfectly without any error!!
Here is my index.js file on express js that includes cookie-parser middleware as well
require("dotenv").config();
const port = process.env.PORT || 5050;
const express = require("express");
const app = express();
const cors = require("cors");
const authRouter = require("./routes/auth");
var cookieParser = require('cookie-parser')
connect_db();
app.use(express.json());
app.use(cookieParser())
app.use(cors());
app.use("/" , authRouter);
app.listen(port , () => {
console.log("Server is running!!");
})
Code for setting up the cookie from express api only controller
const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt')
const login = async (req, res) => {
const { email, password } = req.body;
try {
const checkDetails = await User.findOne({ email });
if (checkDetails) {
const { password: hashedPassword, token, username } = checkDetails;
bcrypt.compare(password, hashedPassword, function (err, matched) {
if (matched) {
res.cookie("token", token, { expires: new Date(Date.now() + (5 * 60000)) , httpOnly: true }).json({ "message": "You logged in sucessfully!" });
} else {
res.status(500).json({ "message": "Wrong password" });
}
});
} else {
res.status(500).json({ "message": "Wrong email" });
}
} catch (error) {
console.log(error.message);
}
}
Here is the react.js code that I am using to fetch data from api without using a proxy in package.json file
if (errors.length === 0) {
const isLogin = await fetch("http://localhost:5000/api/login", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: {
"Content-Type": "application/json"
}
});
const res = await isLogin.json();
if(res) alert(res.message);
}
I want to get to know what is the reason behind this "getting cookie in postman but not in the browser". Do I need to use any react package?
The network tab screenshot might help you.
If I see in the network tab I get the same cookie, set among the other headers
To my understanding, fetch doesn't send requests with the cookies your browser has stored for that domain, and similarly, it doesn't store any cookies it receives in the response. This seems to be the expected behaviour of fetch.
To override this, try setting the credentials option when making the request, like so:
fetch(url, {
// ...
credentials: 'include'
})
or, alternatively:
fetch(url, {
// ...
credentials: 'same-origin'
})
You can read more about the differences between the two here.
I got my error resolved with two changings in my code
In front end just added credentials: 'include'
fetch(url, {
method : "POST"
body : body,
headers : headers,
credentials: 'include'
})
And in back end just replaced app.use(cors()); to
app.use(cors({ origin: 'http://localhost:3000', credentials: true, exposedHeaders: ['Set-Cookie', 'Date', 'ETag'] }))
That's it got resolved, Now I have cookies stored in my browser!!! Great. Thanks to this article:
https://www.anycodings.com/2022/01/react-app-express-server-set-cookie-not.html
during development i also faced same things, let me help you that how i solve it,
Firstly you use proxy in your react package.json, below private one:-
"private": true,
"proxy":"http://127.0.0.1:5000",
mention the same port on which your node server is running
Like:-
app.listen(5000,'127.0.0.1',()=>{
console.log('Server is Running');
});
above both must be on same , now react will run on port 3000 as usual but now we will create proxy to react So, react and node ports get connected on same with the help of proxy indirectly.
Now, when you will make GET or POST request from react then don't provide full URL, only provide the path on which you wants to get hit in backend and get response,
Example:-
React side on sending request, follow like this:-
const submitHandler=()=>{
axios.post('/api/loginuser',
{mobile:inputField.mobile,password:inputField.password})
.then((res)=>{
console.log(res);
})
.catch((err)=>{
console.log(err);
})
}
Node side where it will hit:-
app.post('/api/loginuser', async(req,res)=>{
//Your Code Stuff Here
res.send()
}
on both side same link should hit, it is very important
it will 100%.
don't forget to mention
on node main main where server is listening
I am working on user authentication for a website built using the MERN stack and I have decided to use JWT tokens stored as HttpOnly cookies. The cookie was sent in a "Set-Cookie" field in response header when I used Postman to make the request but not in the Safari Web Inspector as shown in the image below. There are no cookies found in the storage tab either.
I have simplified my React login form to a button that submits the username and password of the user for the sake of debugging
import React from "react";
const sendRequest = async (event) => {
event.preventDefault();
let response;
try {
response = await fetch("http://localhost:5000/api/user/login", {
method: "POST",
body: { username: "Joshua", password: "qwerty" },
mode: "cors",
// include cookies/ authorization headers
credentials: "include",
});
} catch (err) {
console.log(err);
}
if (response) {
const responseData = await response.json();
console.log(responseData);
}
};
const test = () => {
return (
<div>
<input type="button" onClick={sendRequest} value="send" />
</div>
);
};
export default test;
I am using express on the backend and this is my index.js where all incoming requests are first received
const app = express();
app.use(bodyParser.json());
app.use("/images", express.static("images"));
app.use((req, res, next) => {
res.set({
"Access-Control-Allow-Origin": req.headers.origin,
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": "Content-Type, *",
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE",
});
next();
});
app.use(cookieParser());
// api requests for user info/ login/signup
app.use("/api/user", userRoutes);
This is the middleware that the login request is eventually directed to
const login = async (req, res, next) => {
const { username, password } = req.body;
let existingUser;
let validCredentials;
let userID;
let accessToken;
try {
existingUser = await User.findOne({ username });
} catch (err) {
return next(new DatabaseError(err.message));
}
// if user cannot be found -> username is wrong
if (!existingUser) {
validCredentials = false;
} else {
let isValidPassword = false;
try {
isValidPassword = await bcrypt.compare(password, existingUser.password);
} catch (err) {
return next(new DatabaseError(err.message));
}
// if password is wrong
if (!isValidPassword) {
validCredentials = false;
} else {
try {
await existingUser.save();
} catch (err) {
return next(new DatabaseError(err.message));
}
userID = existingUser.id;
validCredentials = true;
accessToken = jwt.sign({ userID }, SECRET_JWT_HASH);
res.cookie("access_token", accessToken, {
maxAge: 3600,
httpOnly: true,
});
}
}
res.json({ validCredentials });
};
Extra information
In the login middleware, a validCredentials boolean is set and returned to the client. I was able to retrieve this value on the front end hence I do not think it is a CORS error. Furthermore, no errors were thrown and all other API requests on my web page that do not involve cookies work fine as well.
Another interesting thing is that despite using the same data (A JS object containing {username:"Joshua", password:"qwerty"}) for both Postman and the React code, validCredentials evaluates to true in Postman and false in the Web Inspector. It is an existing document in my database and I would expect the value returned to be true, which was the case before I added cookies
May I know what I have done wrong or do you have any suggestions on how I can resolve this issue? I am a beginner at web-development
EDIT
With dave's answer I can receive the "Set-Cookie" header on the frontend. However it does not appear in the Storage tab in the web inspector for some reason.
This is the response header
This is the Storage tab where cookies from the site usually appears
If you're trying to send the request as json, you need to set the content type header, and JSON.stringify the object:
response = await fetch("http://localhost:5000/api/user/login", {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: "Joshua", password: "qwerty" }),
mode: "cors",
// include cookies/ authorization headers
credentials: "include",
});
Right now you're probably getting the equivalent of
existingUser = User.findOne({ username: undefined})
and so when you do:
if (!existingUser) {
validCredentials = false;
} else { /* ... */ }
you get the validCredentials = false block, and the cookie is set in the other block.
You can not see it because you have made it httpOnly cookie.
So, finally my MMORTS game built on Sails is going to Kongregate.
Had few obstacles, like connecting websockets, but solved now.
Probably the last obstacle is to keep authenticated session. I was using frameworks everywhere and i have no idea how does the authentication sessions work under the hood.
The main problem is probably the CSRF or CORS. I am using Sails v1.0.
So, i start with HTML, which I upload to kongregate. I'm taking the simplest possible example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<script src="jquery.js"></script>
<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>
<script src="sails.io.js"
autoConnect="false"
environment="production"
headers='{ "x-csrf-token": "" }'
></script>
<script type="text/javascript">
io.sails.url = 'https://my-secret-game.com'; // or where you want
</script>
</head>
<script src="main.js"></script>
</html>
And this is the main.js , which I also upload to kongregate
kongregateAPI.loadAPI(function(){
window.kongregate = kongregateAPI.getAPI();
var username = kongregate.services.getUsername();
var id = kongregate.services.getUserId();
var token = kongregate.services.getGameAuthToken();
$.get("https://my-secret-game.com/csrfToken", function (data, jwres) {
var params = {
username: username,
id: id,
token: token,
_csrf: data._csrf
};
$.post("https://my-secret-game.com/kong", params, function(data, jwr, xhr){
// cant set the cookie - because of chrome. this doesnt work
document.cookie = document.cookie + ';authenticated=true;sails.sid=' + data.id;
$.get("https://my-secret-game.com/csrfToken", function (data, jwres) {
var msg = {
testing_authentication: true,
_csrf: data._csrf
};
$.post("https://my-secret-game.com/test", msg, function(data, status){
// getting the 403 Forbidden, CSRF mismatch. trying to access
// the play/test route, which is protected by sessionAUTH
console.log('data.response', data.response)
});
});
});
});
});
The problem is, that i am getting 403 Forbidden whenever I try to POST my Sails backend with sessionAUTH. I also cant set cookies - probably because of Chrome. What can I do? When i get CSRF token, on the next request my Sails app responds about CSRF mismatch. It becomes wrong.
And this is the controller on my Sails backend server
module.exports = {
kong: function (req, res, next) {
var url = 'https://api.kongregate.com/api/authenticate.json';
var kong_api_key = 'my-secred-api-key';
var params = req.allParams();
var request = require('request');
var req_form = {
"api_key": kong_api_key,
"user_id": params.id,
"game_auth_token": params.token
};
request({
url: url,
method: "POST",
json: true,
body: req_form,
timeout: 5000
}, function (err, response, body){
if(err) { console.log(err, 'ERR43'); return res.ok(); }
else {
if(!response.body.success) {
console.log('unsuccessful login from kongregate')
return res.ok();
}
// trying to use a existing user and authenticate to it
User.find({username: 'admin-user'}).exec(function(err, users) {
var user = users[0];
req.session.authenticated = true;
req.session.user = { id: user.id };
// trying to send session_id, so that i could hold it on kongregates cookies as `sid`
return res.send({ user: user, id: req.session.id });
});
}
});
},
Could somoene please help to fix authentication and CSRF of my app?
In case needs more info about my configs, this is the config/session.js
var prefixes = 'dev';
module.exports.session = {
secret: 'my-secret',
cookie: {
secure: false
},
adapter: 'redis',
host: 'localhost',
port: 6379,
ttl: 3000000,
db: 0,
prefix: prefixes + 'sess:',
};
config/policies.js
module.exports.policies = {
user: {
'new': 'flash',
'create': 'flash',
'edit': 'rightUser',
'update': 'rightUser',
'*': 'sessionAuth'
},
play: {
'*': 'sessionAuth'
}
};
api/policies/sessionAuth.js
module.exports = function(req, res, next) {
if (req.session.authenticated) {
return next();
} else {
var requireLoginErr = [
{ name: 'requireLogin', message: 'You must be signed in' }
];
req.session.flash = {
err: requireLoginErr
};
res.redirect('/');
return;
}
};
config/security.js
module.exports.security = {
csrf: true,
cors: {
allowRequestMethods: 'GET,PUT,POST,OPTIONS,HEAD',
allowRequestHeaders: 'content-type,Access-Token',
allowResponseHeaders: '*',
allRoutes: true,
allowOrigins: '*',
allowCredentials: false,
},
};
Okey, since i had no answers (obviously - the question was bad), answering with my solution which i have solved by my self - so the next time i can read my self. Not sure how good it is, but at least it works.
Sails CORS is taken form Express.js and allows to connect sockets to kongregate if i allow it inside configs.
But it does not allow to authenticate in a normal way, by sending sails.sid (authentication token) via cookies.
Chrome does not allow to set cookies with javascript (i dont have backend on Kongregate) to headers at all due to security. So, if i can't send cookies with headers, Sails can't authenticate the requests in a normal way. Even if i allow CORS to accept the 'cookie' header - it's not allowed by browsers to set cookie headers with javascript.
I can make some unique header like "authentication" and set the sails.sid there, extend some core functionality of Sails to take this new header instead of cookie header. But the problem - on Sails backed i was not able to get at all this sails.sid and send it to my external frontend.. Where it is created? How can i get sails.sid on Sails backend? Not sure - can't google it.
So, i just did authentication in a most simple way possible - on account login/register, i just create a session key by my self - with bcrypt hashing user_id+secret_token (taken from sails config secrets). and sending to the frontend { user_id: 'abcd', secret_token: 'a2dw412515...' }
I have made my policies in Sails to authenticate on every POST/GET request - take the request's session_id and user_id, and compare using bcrypt, does the session_id is the same as encrypted user_id+secret_token. I hope its secure enough.
So, it worked. I just had to disable CSRF. Maybe some day i will implement it again, I just have to write it in my way, not leave the Sails defaults.
The working code:
FRONTEND
// you upload this HTML file to kongregate
// also you upload additionally ZIP named "kongregate_uploaded_folder" with libraries like sails.io, jquery
<!DOCTYPE html>
<html>
<head>
<script src="kongregate_uploaded_folder/jquery.js"></script>
<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>
<script src="kongregate_uploaded_folder/sails.io.js"
autoConnect="false"
environment="production"
></script>
</head>
<body style="padding:0; margin:0; overflow:hidden;">
<div style="position:absolute; margin: 0px; padding: 0px;">
<canvas id="main_canvas" style="position:absolute;" width="640" height="480" >Best initial resolution to have in Kongregate</canvas>
</div>
<script>
// the first thing happends - you try to connect your frontend with Kongregate
kongregateAPI.loadAPI(function(){
window.kongregate = kongregateAPI.getAPI();
if(!kongregate.services.isGuest()) {
var params = {
username: kongregate.services.getUsername(),
id: kongregate.services.getUserId(),
token: kongregate.services.getGameAuthToken(),
};
// call your backend to create a new session and give you session_id
$.post("https://your_game_server.com/kong", params, function(data, jwr, xhr){
var kong_session_id = data.kong_session_id;
var kong_user_id = data.kong_user_id;
var user = data.user;
// connect your sockets with the server in this way
io.socket = io.sails.connect("https://your_game_server.com", { useCORSRouteToGetCookie: false, reconnection: true });
// subscribe to the global sockets channel. You have to make this route and code, but here is a example
io.socket.get('/subscribe', { kong_session_id: kong_session_id, kong_user_id: kong_user_id }, function(data, jwr){
if (jwr.statusCode == 200){
io.socket.on(data.room, function(event){
// on any server-side event, you will get this "event" message. At this part you decide what to do with this data
incoming_socket_event(event); // i wont write this function
});
// your game continues here:
$.get("https://your_game_server.com/player_data?kong_session_id=" + kong_session_id + "&kong_user_id=" + kong_user_id, params, function(data, jwr, xhr){
// you will get authenticated "current_user"
}
});
})
}
});
</script>
</html>
BACKEND
// SAILS BACKEND: home_controller.js
module.exports = {
kong: function (req, res, next) {
// player has already opened your game in kongregate.com and frontend requests this endpoint POST /kong { id: 84165456, token: 'as54..' }
// you need to create a new session for this player, or register this player. This is your own session creation, since default sails session wont work with external website frontend.
var req_params = {
url: "https://api.kongregate.com/api/authenticate.json", // default URL to validate kongregate user
method: "POST",
json: true,
body: {
api_key: 'gg000g00-c000-4c00-0000-c00000f2de8', // kongregate will provide this api-key for server-side connection (this one has some letters replaced)
user_id: 84165456, // when frontend requests POST /kong { id=84165456 } , this 84165456 is provided by kongregate in the frontend
game_auth_token: "as54a45asd45fs4aa54sf" // when frontend requests POST /kong { token = 'as54..' }, this is provided by kongregate in the frontend
},
timeout: 20000
}
// request kongregate that this is the real player and you will get a username
request(req_params, function (err, response, body){
var response_params = response.body; // response from kongregate API
// search for user with this kongregate_id inside your database, maybe he is already registered, and you need just to create a new session.
User.find({ kongregate_id: response_params.user_id }).exec(function(err, usr) {
var user = usr[0]
// if player already has an account inside your online game
if(user) {
// create new session for this user.
require('bcryptjs').hash("your_own_random_secret_key" + user.id, 10, function sessionCreated(err, kong_session_id) {
// send this info to frontend, that this player has been connected to kongregate
return res.send({
user: user,
kong_session_id: kong_session_id,
kong_user_id: user.id
});
});
//if this is new user, you need to register him
} else {
var allowedParams = {
username: response_params.username, // kongregate will give you this player username
email: 'you_have_no_email#kong.com', // kongregate does not provide email
password: 'no_password_from_kongregate',
kongregate_id: response_params.user_id // kongregate will give you this player id
};
User.create(allowedParams, function(err, new_user) {
// create new session for this user.
require('bcryptjs').hash("your_own_random_secret_key" + new_user.id, 10, function sessionCreated(err, kong_session_id) {
// send this info to frontend, that this player has been connected to kongregate
return res.send({
user: new_user,
kong_session_id: kong_session_id,
kong_user_id: new_user.id
});
});
});
}
});
});
},
};
ROUTES
// config/routes.js
module.exports.routes = {
'GET /player_data': 'PlayController.player_data',
'GET /subscribe': 'PlayController.subscribe',
'POST /kong': {
action: 'home/kong',
csrf: false // kongregate is a external website and you will get CORS error without this
},
};
SECURITY
// config/security.js
module.exports.security = {
csrf: false,
cors: {
allowOrigins: ['https://game292123.konggames.com'], // your game ID will be another, but in this style
allowRequestMethods: 'GET,POST',
allowRequestHeaders: 'Content-Type',
allowResponseHeaders: '',
allRoutes: true,
allowCredentials: false,
},
};
SOCKETS
// config/sockets.js
module.exports.sockets = {
grant3rdPartyCookie: true,
transports: ["websocket"],
beforeConnect: function(handshake, cb) { return cb(null, true); },
};
CONFIG POLICIES
// /config/policies.js
module.exports.policies = {
play: {'*': 'sessionAuth'},
};
API POLICIES
// /app/sessionAuth.js
module.exports = function(req, res, next) {
var params = req.allParams();
// your own session handling way to get the user from session token
require('bcryptjs').compare("your_own_random_secret_key" + params.kong_user_id, params.kong_session_id, function(err, valid) {
req.session.authenticated = true;
req.session.user_id = params.kong_user_id;
return next();
});
};
CONTROLLER
// /api/controllers/PlayController.js
module.exports = {
player_data: async function (req, res, next) {
var users = await User.find(req.session.user_id);
return res.send({ current_user: users[0] });
},
subscribe: async function (req, res, next) {
var users = await User.find(req.session.user_id);
var roomName = String(users[0].id);
sails.sockets.join(req.socket, roomName);
res.json({ room: roomName });
},
}
I'm having trouble scraping a website that needs authentication, and is using session cookies. The session requires a request with POST, and the authentication then approves. But when I want to GET the webpage that need authentication, it returns "Unauthorized". I guess I need a way to bring the session cookie with the GET-request, but I don't know how! My dependencies is request-promise(https://www.npmjs.com/package/request-promise).
The code looks like this:
var rp = require("request-promise");
var options = {
method: "POST",
uri: "http://website.com/login",
form: {
username: "user",
password: "pass",
},
headers: {},
simple: false
};
rp(options).then(function(response) {
console.log(response); // --> "Redirecting to login/AuthPage"
request("http://website.com/login/AuthPage", function(err, res, body) {
console.log(body); // --> "Unauthorized"
})
}).catch(function(e) {
console.log(e)
})
I'm guessing you have to put the request in a "Jar" (https://github.com/request/request#requestjar), to be able to reach the next request-URL, but how can I set the request-promise to create a cookie-jar?
Your problem is how to keep the session after authentication.
That means, after logging in by using username and password, the server will return a cookie with an identifier. Then you need to attach that cookie to all your feature requests.
It's simple with request-promise. Just keep tracking session by enabling jar option then use the same request object for all requests.
Let take a look
var request = require("request-promise").defaults({ jar: true });
var options = {
method: "POST",
uri: "http://website.com/login",
form: {
username: "user",
password: "pass",
},
headers: {},
simple: false
};
request(options).then(function(response) {
request("http://website.com/login/AuthPage", function(err, res, body) {
console.log(body);
})
}).catch(function(e) {
console.log(e)
})
Use the following object while making rest calls.
var request = require("request-promise").defaults({jar: true});
To add your own cookies
var tough = require('tough-cookie');
// Easy creation of the cookie - see tough-cookie docs for details
let cookie = new tough.Cookie({
key: "some_key",
value: "some_value",
domain: 'api.mydomain.com',
httpOnly: true,
maxAge: 31536000
});
// Put cookie in an jar which can be used across multiple requests
var cookiejar = rp.jar();
cookiejar.setCookie(cookie, 'https://api.mydomain.com');
// ...all requests to https://api.mydomain.com will include the cookie
var options = {
uri: 'https://api.mydomain.com/...',
jar: cookiejar // Tells rp to include cookies in jar that match uri
};
and then make the call. More details about request-promise:
https://www.npmjs.com/package/request-promise