gpt4 book ai didi

reactjs - 结合基于 NodeJS 的 Passport 身份验证和 ReactJS 前端

转载 作者:行者123 更新时间:2023-12-02 20:23:47 25 4
gpt4 key购买 nike

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

现在我正在 :3000 上构建一个 ReactJS 前端。它应该将 AJAX 调用发送到后端,并附加身份验证 token 作为查询字符串参数。我已将端口转发添加到客户端的 package.json,以便正确处理所有 AJAX 调用。

我不知道如何将身份验证 token (从 http://localhost:3001/auth/github/callback 作为 cookie 接收)发送到客户端。虽然我的 AJAX 调用已正确代理,但当我导航到/auth/github 时,我仍然位于 React 生成的页面上,并且我的 :3001 端点未被命中。如果我访问 :3001/auth/github,我的前端代码不会获取 auth_token cookie。

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

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

最佳答案

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

express 示例

路由.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
}

Passport 初始化

// 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
}

react

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

关于reactjs - 结合基于 NodeJS 的 Passport 身份验证和 ReactJS 前端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50568645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com