How to use the passport authentication in express application - express

var passport = require('passport')
var passportLocal = require('passport-local');
var expressSession = require('express-session');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(expressSession({
secret: process.env.SESSION_SECRET || 'secret',
resave: false,
saveUninitialized: false
}))
passport.use(new passportLocal.Strategy(function(username, password, done) {
if (username == password) {
done(null, { id: username, name: username });
} else {
done(null, null);
}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(null, { id: id, name: id });
});
app.use('/', index);
app.use('/', users);
app.get('/', function(req, res, next) {
res.render("login", {
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
app.post('/login',
passport.authenticate('local'),
function(req, res, next) {
res.redirect("/index1");
});
Got that to work....But how do I restrict access to all pages ?

Got that working!!!
Here is the code:
var passport = require('passport')
var passportLocal = require('passport-local');
var expressSession = require('express-session');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/node_modules/jquery/dist/'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(expressSession({
secret: process.env.SESSION_SECRET || 'secret',
resave:false,
saveUninitialized: false
}))
passport.use(new passportLocal.Strategy(function(username,password, done){
if(username == password)
{
done(null,{ id:username, name: username });
}
else
{
done(null,null);
}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user,done){
done(null,user.id);
});
passport.deserializeUser(function(id,done){
done(null, { id:id,name: id});
});
app.use('/', index);
app.use('/', users);
app.get('/', function(req, res, next) {
res.render("login",{
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
app.post('/login',
passport.authenticate('local'), function(req, res, next) {
res.redirect("/index1");
});
and then use the following conditional logic:
if(req.isAuthenticated())
{
}
else
{
}

Related

passport.use is not being called

I want to learn how to use passport js, so I created a dummy project with front-end and express back-end, the front-end form is sending a post request to "/emailAndPassword" route on express.
the request is sent successfully but passport.use is not being called and the authenticate middleware is allway redirected to "/failure" route.
Can anybody help me, the code is here:
const express = require("express");
const cors = require("cors");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const session = require("express-session");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: "secret",
saveUninitialized: false,
resave: false,
})
);
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
function(username, password, done) {
return done(null, { username: "rest#test.com", password: "some-characters" });
}
)
);
app.use(passport.initialize());
app.use(passport.session());
app.get("/", (req, res) => {
res.send("success");
});
app.get("/failure", (req, res) => {
res.send("failure");
});
app.post(
"/emailAndPassword",
passport.authenticate("local", {
failureRedirect: "/failure",
successRedirect: "/",
}),
(req, res) => {
res.redirect("/")
}
);
app.listen(5000, () => {
console.log("listening...");
});
Try to put passport.use() function below passport.initialize()
Like:
app.use(passport.initialize())
app.use(passport.session())
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
function(username, password, done) {
return done(null, { username: "rest#test.com", password: "some-characters" });
}
)
)

Why do I keep getting this error when trying to set up passport-local-mongoose, after registering a user?

Every time i try to register a new username and password i get this error. Error Message Im not sure if I am doing something wrong. I am trying to learn the different levels of authentication
my code is below
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs',);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'suckbigd please',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
// mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
email: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/login", function (req, res) {
res.render("login");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets");
} else {
res.render("/login");
}
});
app.post("/register", function (req, res) {
User.register({ username: req.body.username }, req.body.password, function (err, user) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.post("/login", function (req, res) {
const usetr = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, function (err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
})
});
app.listen(3000, function () {
console.log("Server started on port 3000.");
});
I thought I followed the course instructions right. I even watched the video and followed along but I am still getting this error. I am banging my head on the key board. I have been trying to fix this for 4 days now and still nothing. Someone please help.

Heroku to netlify session wont store session values

This works fine when I am running it on Localhost3000(client) and localhost:3005(server). However once I publish my app to Heroku(server) and netlify(client) it for some reason tells me the req.session.steamuser when accessing /user is null even after it has been set in /api/auth/steam/return and I have tested that the req.session.steamuser=req.user accutally work.
Server.js
var express = require('express');
var passport = require('passport');
var session = require('express-session');
var passportSteam = require('passport-steam');
const cors = require("cors");
var SteamStrategy = passportSteam.Strategy;
var app = express();
const corsOptions = {
origin: ["https://stunning-bavarois-0eef55.netlify.app"],
credentials: true, //access-control-allow-credentials:true
methods: ["GET", "POST"],
};
app.use(cors(corsOptions));
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
passport.use(new SteamStrategy({
returnURL: 'https://temtestt.herokuapp.com/api/auth/steam/return',
realm: 'https://temtestt.herokuapp.com/',
apiKey: 'MY SECRET API KEY'
}, function (identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
app.use(session({
secret: 'db5910cc8b9dcec166fda1d2c34860b6f8cd932cea641ea39924ed18fe6fc863',
resave: true,
saveUninitialized: true,
cookie: {
SameSite:"none",
maxAge: 3600000,
secure:true
}
}))
// Initiate Strategy
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.status(200);
res.send("Welcome to root URL of Server");
});
app.get("/user", (req, res) => {
if (req.session.steamuser) {
res.status(200).send(req.session.steamuser)
}
else {
res.send(false)
}
})
app.get('/api/auth/steam', passport.authenticate('steam', { failureRedirect: '/' }), function (req, res) {
res.redirect('/')
});
app.get('/api/auth/steam/return', passport.authenticate('steam', { failureRedirect: '/' }), function (req, res) {
req.session.steamuser = req.user;
res.redirect('https://stunning-bavarois-0eef55.netlify.app/')
});
app.listen(process.env.PORT || 3005);
Client
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [user,setUser]=useState(null);
useEffect(()=>{
async function getUser(){
const data = await axios.get("https://temtestt.herokuapp.com/user",{withCredentials:true});
setUser(data.data);
}
getUser();
},[]);
return (
<div className="App">
<h1>Hello</h1>
{(user===false||user===null)?<><p>Please log in</p>Login</>:<p>{user.displayName}</p>}
</div>
);
}
export default App;
As mentioned already it works fine when I do with localhost and returns correct values. But when I try with netlify and heroku it almost seems like it doesn't recognize the session key or something.

cant get current User from API with axios

i have a problem to get my auth User. When I call my route where the current user is in i become no Data in my Vue file.
Backend:
var app = express();
app.use(cors({
methods:['GET','POST'],
credentials: true,
}))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser('test'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'test',
resave: true,
saveUninitialized: true,
}))
app.use(passport.initialize());
app.use(passport.session());
const port = 3000
app.use(express.static('public'))
//Passport setup
const apiRoutes = require('./apiRoutes')
app.use('/api', apiRoutes)
Passport config:
passport.use(new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
userModel.findOne({
username: username
}, (req, res) => {
const match = bcrypt.compare(password, res.password).then(result => {
if (result) {
return done(null, res, {message: 'hat geklappt'})
} else {
return done(null, false, {message: 'hat nicht geklappt'})
}
})
})
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
Route:
router.get("/", (req, res) => {
let user = req.user;
res.json(
user
);
});
My API is not empty but i cant get the data from Axios get
API:
APi
and my Empty data field:
vue
i dont know what i can do because i have not so much experience and iam really thankfull for help
Thanks :)
set content-type: application/json in the header like this:
it's a sample
var axios = require('axios');
var data = JSON.stringify({"username":"username","password":"password"});
let domain = "localhost";
let port = "3000"
let url = `http://${local}:${port}/api`
var config = {
method: 'post',
url: '',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
the request is not added to the question, but you can change your request base on my answer

CloudFlare set-cookie not passing through to browser

I have an express application behind CloudFlare. In development, the Set-Cookie header gets passed on login, but behind CloudFlare, the Set-Cookie header is not passed. Any suggestions? My config is:
```
import passport from 'passport';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import { Strategy as LocalStrategy } from 'passport-local';
import localPassport from '../../db/sequelize/passport';
const secret = 'foo';
const authenticationMiddleware = (req, res, next) => {
console.log('authenticated', req.isAuthenticated());
if (req.isAuthenticated()) {
next();
} else if (req.url.includes('/rest/')) {
res.status(401).send('Unauthorized');
} else {
res.status(302).redirect('/admin/login');
}
};
const sessionSecurity = (app) => {
app.set('trust proxy', 1);
app.use(cookieParser(secret));
app.use(
session({
secret,
proxy: true,
saveUninitialized: false,
resave: false,
maxAge: null,
cookie: {
path: '/admin',
secure: process.env.NODE_ENV === 'production',
},
}),
); // session secret
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(localPassport.local));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(localPassport.deserializeUser);
app.post('/admin/login', (req, res, next) => {
passport.authenticate('local', (authErr, user) => {
if (authErr) return next(new Error(authErr));
if (!user) {
return res.sendStatus(401);
}
return req.logIn(user, (loginErr) => {
if (loginErr) return res.sendStatus(401);
return res.sendStatus(200);
});
})(req, res, next);
});
app.post('/admin/logout', (req, res) => {
req.logOut();
req.session.destroy(() => {
res
.clearCookie('connect.sid', { path: '/admin' })
.sendStatus(200);
});
});
app.get('/admin/rest/*', authenticationMiddleware);
app.get('/admin/rest/status', (req, res) => {
res.sendStatus(200);
});
};
```
This was caused because the server settings where set to cookie secure and the connection between CloudFlare and my server were not.
In setting of cloudflare (crypto tab), I turned on "Authenticated Origin Pulls" and in "app.js" (from my app) add this app.set('trust proxy', 1);
before app.use(session({...}) and my problem solved.