前面读取来自nodejs的cookie(Reactjs)

问题描述 投票:0回答:1

我需要获取已在节点js路由文件中定义的cookie(这是一个令牌)到我的前面,因为我需要检查此令牌的信息以显示是用户还是管理员的数据。

这是cookie的一些代码:

// auth with google+
router.get('/auth/google', passport.authenticate('google', {
    scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email'
    ]
}));
// callback route for google to redirect to
// hand control to passport to use code to grab profile info
router.get('/auth/google/callback*', passport.authenticate('google'), (req, res) => {
    if(req.user){
        console.log(req.user);
        res.cookie('token', req.user);
        return res.redirect(config.clientURL);
    }
    else{
        console.log('error');
        return res.redirect(config.clientURL);
    }
});
// auth with faceboook
router.get('/auth/facebook', passport.authenticate('facebook'));
// callback route for facebook to redirect to
// hand control to passport to use code to grab profile info
router.get('/auth/facebook/callback*', passport.authenticate('facebook'), (req, res) => {
    console.log("je suis dans la route callback");
    if(req.user){
        console.log(req.user);
        res.cookie('token', req.user);
        return res.redirect(config.clientURL);
    }
    else{
        console.log('error');
        return res.redirect(config.clientURL);
    }
});

谢谢

reactjs session-cookies google-authentication
1个回答
0
投票

正如我在评论中提到的,设置cookie时使用httpOnly标志是一个很好的建议;这意味着您需要另一种策略来返回用户数据。

选项1:一种更易于实现的方式可能是:服务器将客户端重定向到假设为/logged-in后,您可以从假设为/api/userinfo来获取用户数据;响应应为包含用户信息的json;您应该使用该json通过localStorate.setItem(...)将信息存储在客户端中。这是将用户数据存储在客户端中的经典且更常用的方法。

示例服务器(创建返回已登录用户信息的端点):

// Server endpoint that returns user info
router.get('/api/userinfo', 
passport.authenticate(your_strategy_here), 
(req, res) => {
  res.json({ name: req.user.name, role: req.user.role }); // Return just what you need
})

示例客户端(创建一个从新服务器端点请求用户信息的组件):

componentDidMount(){
  fetch('/api/userinfo')
  .then( res => res.json() )
  .then( user => localStorate.setItem('user', user);
}

选项2:给Google一个由客户端解析的URL,然后让客户端将请求发送到/auth/facebook/callback;然后让服务器执行res.json(user),而不是执行重定向。

Google -> /your-client-app/auth/callback

Client -> /auth/facebook/callback

选项2是我的建议,但是,对于您当前的设置,选项1可能更直接。

© www.soinside.com 2019 - 2024. All rights reserved.