首页 > 解决方案 > 读取来自nodejs的前面的cookie(Reactjs)

问题描述

我需要获取已在我前面的节点 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);
    }
});

编辑 :

我这样做了:

const auth_head =  document.cookie.split('.')[0];
        const auth_payload =  document.cookie.split('.')[1];
        const auth_signature =  document.cookie.split('.')[2];
        var auth_token = auth_head + "." + auth_payload + "." + auth_signature;

 console.log(JSON.parse( auth_head));
            console.log(JSON.parse( auth_payload));
            console.log(JSON.parse( auth_signature));

但我得到了这个错误: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1

谢谢

标签: reactjssession-cookiesgoogle-authentication

解决方案


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

选项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 可能更直接。

选项 3:在设置 cookie 时禁用 httpOnly,这样做存在安全问题,并不意味着在生产应用程序中这样做。

res.cookie('token', req.user, { httpOnly: false });

然后在您的客户端上,您可以使用以下数据来检查 cookie。

const cookieData = document.cookie;
console.log(cookieData)

推荐阅读