1
votes

I have an API on node.js, with express. This API logs the user in. I use passsport to authenticate it.

I have two routes: / login and / companies. To begin with, the user must log in to the system, he receives the tokens and I log in. After that, he / she must access the route / companies, however, they must be logged in.

To validate if the user is logged in, I use the req.user. Here is the code for user login verification on the route / companies:

exports.list = function (req, res, next) {

console.log(req.user);

if (!req.user) {
    return res.status(404).send("Precisa estar logado.");
}
...

Here are my server settings:

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: 'MotomcoGroupAjm999MOTOMCO',
    resave: false,
    saveUninitialized: true,
    cookie: { httpOnly: false }
}))

// Flash - Gerenciador de mensagens de resposta do servidor.
app.use(flash());
app.use(pass.initialize());
app.use(pass.session());

When doing tests with Postman, I can access / companies without problems, but when I try to access, after login, by the browser, I fall into (!req.user).

Is this a question of cookies? I have tried to use, when making the request to the server with the Angular, withCredentials, however, without success.

Question: Why is the session being written to the tests with Postman but is not recorded in the browser, when I test with Angular? What am I forgetting to do on the client side?

1
Your question is somehow not clear. What is the request parameters you send? Do you store your token anywhere in your application and also send it back to server with every request?Harun Yilmaz
I'm using passport - req.logIn. When I log in with postman, the req.user is not undefined. But, when i log in with browser (with Angular), req.user is undefinedMatheus Bernardi

1 Answers

0
votes

The problem was with CORS. This is what I did to solve the problem:

var cors = require('cors');
app.use(cors({origin:true,credentials: true}));

And, set the headers:

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
    if (req.method === "OPTIONS") {
        return res.status(200).end();
    } else {
        next();
    }
});