在尝试使用react JS发送post请求时,用户未经过身份验证

时间:2017-02-14 10:33:01

标签: javascript node.js mongodb reactjs passport.js

我正在关注一个视频教程,该教程展示了如何使用node和passport JS对用户进行身份验证。本教程使用Hogan JS作为其视图引擎,但我希望使用React作为我的前端, 一切正常在服务器端,如果我用postman测试它,即用户经过身份验证,序列化,反序列化并且会话被存储,但是一旦我从我的反应中访问它时尝试它,用户就不会得到即使我在序列化函数中获得了正确的用户,也会进行身份验证。

这是我的服务器文件:

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)
;

这是我的Passport文件:

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);
  });
});

以下是react登录组件:

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>
    );
  }
}

关于我项目的完整链接,请点击此处 Github Link

1 个答案:

答案 0 :(得分:0)

哇,我刚刚想出答案,我只需要包括:

credentials: 'include',

在fetch方法中,并设置标头以允许我的服务器来源并将allow credential标头设置为true,这是我如何做到的:

res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);

这花了我一整天时间来解决这个问题。