I am following a video tutorial which shows how to authenticate a user using node and passport JS. This tutorial uses Hogan JS for as its view engine, however I want to follow the tutorial using React as my front end, everything works fine on the server side, if I test it with postman, ie, the user is authenticated, serialized, deserialized and the session gets stored, but as soon as I try it while accessing it from my react, The user does not get authenticated even though I am getting a correct user at the serialize function.
Here is my server file:
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
require('./passport');
express()
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: false}))
.use(session({ secret: 'i love dogs', resave: false, saveUninitialized: false }))
.use(passport.initialize())
.use(passport.session())
.get('/', (req, res, next) => {
res.json({
session: req.session,
user: req.user,
authenticated: req.isAuthenticated()
});
})
.get('/login', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.json({name: 'login again'});
})
.post('/login', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
}, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}))
.listen(3001)
;
Here is my Passport file:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('./db');
const ObjectId = require('mongodb').ObjectId;
passport.use(new LocalStrategy(authenticate));
function authenticate (email, password, done) {
mongo.db.collection('users').find({email}).toArray((err, user) => {
if (err) return done(null, false, {message: err});
if (user.length === 0 || user[0].password !== password) {
return done(null, false, {message: 'Invalid user and password combination'});
}
done(null, user);
});
}
passport.serializeUser((user, done) => {
done(null, user[0]._id);
console.log(user);
});
passport.deserializeUser((id, done) => {
console.log(id);
mongo.db.collection('users').find({_id: ObjectId(id)}).toArray((err, user) => {
if (err) return done(null, false, {message: err});
done(null, user);
});
});
and here is the react login component:
import React, {Component} from 'react';
export default class Login extends Component {
constructor (props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit (e) {
e.preventDefault();
const { username, password } = this.refs;
fetch(`http://localhost:3001/login?username=${username.value}&password=${password.value}`, {
method: 'post'
})
.then(blob => blob.json())
.then(res => {
console.log(res);
});
}
render () {
return (
<form onSubmit={this.onFormSubmit}>
<div>
<label>Email:</label>
<input type='text' ref='username' />
</div>
<div>
<label>Password:</label>
<input type='password' ref='password' />
</div>
<div>
<input type='submit' value='Log In' />
</div>
</form>
);
}
}
For the complete link of my project, here's the Github Link
Wow, I just figured out the answer,I just had to include:
credentials: 'include',
in the fetch method, and the set the headers to allow my server origin and set the allow credential headers to be true, here's how I did it:
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);
This took me a whole day to get to this solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.