结合基于NodeJS的护照身份验证和ReactJS前端

时间:2018-05-28 14:33:04

标签: reactjs oauth-2.0 passport.js loopbackjs

我使用带有护照身份验证的Loopback构建了一个后端。它要求我首先访问http://localhost:3001/auth/github,它会重定向到GitHub,它会显示一个登录页面,或者在端口3001上重定向回我的应用程序。

现在我正在构建一个ReactJS前端:3000。它应该向后端发送AJAX调用,并将auth令牌作为查询字符串参数附加。我已将端口转发添加到客户端的package.json,因此可以正确处理所有AJAX调用。

我无法想象的是如何将身份验证令牌(作为cookie从http://localhost:3001/auth/github/callback)收到客户端。当我的AJAX调用被正确代理时,当我导航到/ auth / github时,我仍然在React生成的页面上,而我的:3001端点没有被命中。如果我去:3001 / auth / github,我没有通过我的前端代码获取我的auth_token cookie。

换句话说,我有两个问题: 1.如何从前端导航到我的后端的身份验证页面(http://localhost:3001/auth/github)? 2.如何将#1中获得的cookie添加到我的前端,以便可以在后续查询中使用?

当我正在构建一个演示时,我只需要一个快速而肮脏的解决方案Just Works,但我愿意考虑其他想法,比如打开弹出窗口和/或IFrame。

2 个答案:

答案 0 :(得分:1)

如果您正在使用Passport,则只需阅读策略文档即可。 我假设认证是通过Oauth完成的

快递示例

Routes.js

api.route('/auth/github')
    .get(PassportCtrl.auth);

  api.route('/auth/github/callback')
    .get(PassportCtrl.authCallback, PassportCtrl.redirect);

PassportCtrl.js

import passport from 'passport';

const auth = passport.authenticate('github', {
  scope : ['profile', 'email']
});

const authCallback = passport.authenticate('github');

const redirect = (req, res) => {
    res.redirect('/whereveryouwant');
}

const getAuthUser = (req, res) => {
  res.json({
    user : req.user
  })
}

const logOut = (req, res) => {
  req.logOut();

  res.redirect('/');
}

export default {
  auth,
  authCallback,
  redirect,
  getAuthUser,
  logOut
}

护照初始

// adding cookie feature
app.use(cookieSession({
  maxAge : 30 * 24 * 60 * 60 * 100,
  keys : [process.env.COOKIE_SECRET]
}));

// initializing passport
app.use(passport.initialize());
app.use(passport.session());

我忘记了,你必须代理

webpack.config.js

 devServer: {
    proxy: { // proxy URLs to backend development server
      '/auth/github': 'http://localhost:3001',
      '/api/**' : {
        'target' : 'http://localhost:3001'
      }
    },
    hot : true,
    contentBase: path.join(__dirname, "dist"),
    historyApiFallback : true,
    compress: true,
    port: 8080
  }

阵营

import React from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';


class Header extends React.Component {
  renderContent () {
    const {auth} = this.props;
    switch (auth) {
      case null : return;
      case false : return (
        <li><a href='/auth/google'>Login with google</a></li>
      )
      default: return ([
        <li key={'logout'}><a href='/api/logout'>Log out</a></li>
      ])
    }
  }
  render () {
    const {auth} = this.props;
    return (
      <nav>
        <div className='nav-wrapper'>
          <Link className="left brand-logo" to={auth ? '/whereveryouwant' : '/'}>
            Your page Name
          </Link>
          <ul className='right'>
            {this.renderContent()}
          </ul>
        </div>
      </nav>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    auth : state.auth
  }
}

export default connect(mapStateToProps)(Header);

答案 1 :(得分:1)

有一些建议可以解决它:

  1. 如何从前端导航到我的后端的身份验证页面(http://localhost:3001/auth/github)?
  2. 在React客户端上使用Proxy(在package.json中) 例如:

     {
      "name": "client",
      "version": "0.1.0",
      "private": true,
      "proxy": {
        "/auth/github": {
          "target": "http://localhost:3001"
        },
        "/api/*": {
          "target": "http://localhost:3001"
        }
      },
      "dependencies": {
        "axios": "^0.16.2",
        "materialize-css": "^0.99.0",
        "react": "^16.0.0-alpha.13",
        "react-dom": "^16.0.0-alpha.13",
        "react-redux": "^5.0.5",
        "react-router-dom": "^4.1.1",
        "react-scripts": "1.0.10",
        "react-stripe-checkout": "^2.4.0",
        "redux": "^3.7.1",
        "redux-form": "^7.0.1",
        "redux-thunk": "^2.2.0"
      },
    }
    

    因此,当您从前面访问api时,您可以使用&#39; / auth / github&#39;

    直接引用它。
    1. 如何将#1中获得的cookie添加到我的前端,以便可以在后续查询中使用?
    2. 我不确定Loopback后端,但是当我使用Express时,您可以使用护照中的passport.session()来设置会话cookie

      希望这会有所帮助。