如果您使用的是 Passport,那么您只需要阅读策略文档。我假设身份验证是通过 Oauth 完成的
以快递为例
路由.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);