Passportjs req.isAuthenticated always shows false

jose

i am worked nodejs/Angular passport middleware login Authentication working fine but when I try to get login username with the help of req.authentication's not call the passport.deserializeUser function always req.authentication is shown false help how to rectify this problem any ideas. here i pasted my tried code

Server.js

const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
// const logger = require('morgan');
var cookieParser = require('cookie-parser');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const dotenv = require('dotenv');
const path = require('path');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
const expressValidator = require('express-validator');
const http = require('http');
const app = express();
// cros origin handling method start
const cors = require('cors');

dotenv.load({ path: '.env.Config' });
app.use(bodyParser.json());

app.use(express.static(__dirname + "/public"));
app.set('views', __dirname + '\\public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//mongodb config
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on('error', () => {
    console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
    process.exit();
});
app.use(cookieParser(process.env.SESSION_SECRET));
app.enable('trust proxy'); // add this line
//express session config
app.use(session({
    name: 'UpgradeApp.sid',
    resave: true,
    //    saveUninitialized: true,
    secret: process.env.SESSION_SECRET,
    store: new MongoStore({
        url: process.env.MONGODB_URI,
        autoReconnect: true
    }),
    proxy: true, // add this line
    saveUninitialized: false,
    cookie: {//New
        maxAge: 36000000,
        httpOnly: false,
        secure: false
    }

}));

require('./src/SchemaConfig/PassportConfig');
//cors origin config
app.use(cors({
    origin: ['http://localhost:4200', 'http://127.0.0.1:4200', 'http://192.168.1.93:4200'],
    credentials: true
}));
//bodyparser config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb", extended: true, parameterLimit: 200000 }));
app.use(passport.initialize());
app.use(passport.session());


//schema config

const UserConfig = require('./src/SchemaConfig/UserSchema');


function isAuthenticated(req, res, next) {
    var ss = req.isAuthenticated();//always show false
    if (req.isAuthenticated()) next();
    else return res.json('Un-Authenticated');

};
app.get('/logout', isAuthenticated, function (req, res) {
    req.logout();
    res.json("logout");
});
app.get('/GetUser', isAuthenticated, function (req, res, next) {
    return res.json(req.user.UserName);
});

app.post('/login', UserConfig.loginVerify);




app.set('port', process.env.App_PORT || 3000);
app.listen(app.get('port'), () => {
    console.log('%s server running on port', chalk.green('✓'), app.get('port'));
    console.log('  Press CTRL-C to stop\n');
});

PassportConfig

const User = require('../SchemaConfig/UserSchema');
var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt-nodejs');

passport.use('local', new LocalStrategy({
    usernameField: 'Email',
    passwordField: 'Password'
},
    function (Email, Password, done) {
        debugger
        User.findOne({ Email: Email }, function (err, user) {
            debugger
            if (err) { return done(err); }
            if (!user) {
                return done(null, false, {

                    ErrorMsg: 'Incorrect Email.'

                });
            }
            if (user) {
                GlobalUserPwd = user.Password;
            }
            if (!ComparePassword(Password)) {
                return done(null, false, {

                    ErrorMsg: 'Incorrect password.'

                });
            }
            return done(null, user);
        });
    }
));


passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});


function ComparePassword(CandidatePassword) {

    return bcrypt.compareSync(CandidatePassword, GlobalUserPwd)
};

Userschema

 exports.loginVerify = (req, res, next) => {
        passport.authenticate('local', function (err, user, info) {
            debugger
            if (err) { return next(err); }
            if (!user) { return res.status(501).json(info); }
            req.logIn(user, function (err) {
                if (err) { return next(err); }
                 return res.status(200).json({message:'Login Success'});

            });
        })(req, res, next);
    };
jose

Finally i found a solution for my problem passing login header request with withCredentials:true

const httpOptions = {
  observe:'body',
  withCredentials:true,
  headers:new HttpHeaders().append('Content-Type','application/json')
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

req.isAuthenticated always returns false

Node js passport's req.isAuthenticated returns always false

passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)

Express-session + Passport + MongoDB - req.isAuthenticated() always return false after login

Passport isAuthenticated() always returns false?

passport req.isAuthenticated() always returns fasle

isAuthenticated always false using Javascript express and passport

Request.IsAuthenticated always returning false on Login

IDE shows condition always false

Excel If Statement always shows false

IsAuthenticated is false

CustomRequestCultureProvider: context.User.Identity.IsAuthenticated is always false

User.Identity.IsAuthenticated always false after PasswordSignInAsync gives success

HttpContext.Current.User.Identity.IsAuthenticated = false always in Nginx Enviroment

User.Identity.IsAuthenticated always false in .net core custom authentication

Setting up passport for the first time. isAuthenticated() always returning false

How to fix isAuthenticated=false and no req.user data after successful login

Powershell Umlaute check shows always false

PassportJS req.user not deserializing

req.isAuthenticated() changes on redirect?

req.session.passport and req.user blank , and req.isAuthenticated returns false after initial successful login using passport-facebook

isAuthenticated is always null

isAuthenticated() always returns true

isAuthenticated return function false

Azure AD API returns System.Security.Principal.GenericIdentity.IsAuthenticated as false always

Jwt Bearer Authentication middleware always sets User.Identity.IsAuthenticated to false

IsAuthenticated is always false in Custom Authorization Attribute (.NET Core 2.2 and Jason Web Token)

User.Identity.IsAuthenticated always return false .NET CORE C#

koa-passport w/ passport-steam: ctx.isAuthenticated() always false