【问题标题】:how can I send token in header authentication Bearer to Browser如何将标头身份验证承载中的令牌发送到浏览器
【发布时间】:2019-02-19 01:42:44
【问题描述】:

这是我在辅助登录路由器中的代码 所以我在确认登录后尝试将cookie设置为浏览器

exports.signin = (req,res) => {
        db.User.findOne({email:req.body.email}).then(user => {
            user.comparePassword(req.body.password,function(err,isMatch){
                if(isMatch){
                    let token = jwt.sign({userId: user.id},process.env.SECRET_KEY,{ expiresIn: 60*5 });
                    res.setHeader() //here I wanna send header Bearer to the browser 
                } else {
                    res.status(400).json({message:"Incorrect Password!"});
                }
            })
        })
        .catch(err => {
            return res.status(404).send('No user found.');  
        })**strong text**
    }

【问题讨论】:

    标签: node.js express cookies jwt restful-authentication


    【解决方案1】:

    在 Node.js res.setHeader() 和 Express js 中 res.header() 是 res.set() 方法的别名。

    您可以通过以下方式使用:

    res.setHeader('Authorization', 'Bearer '+ token); 
    res.header('Authorization', 'Bearer '+ token);
    

    但我建议你阅读 jwt 示例(angularjs & node):https://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs--cms-22543

    【讨论】:

      【解决方案2】:

      Authorization header是一个client header,不能在服务端设置(服务端不需要授权)。您需要在 JSON 响应中发送它,然后在客户端进行处理。

      您的服务器发送带有令牌的 JSON 响应。 您的客户端设置 Authorization 标头并将其发送到任何需要授权的路由

      javascript 客户端示例:

      var myHeaders =  new Headers()
      
      /**you need to get the token and put it in myToken var.
         Where to store the token is the real question, you need
         to take care about the storage you choose beacause of
         the security risks*/
      
      myHeaders.append('Content-Type','application/json; charset=utf-8');
      myHeaders.append('Authorization', 'Bearer ' + myToken);
      
      fetch( '/myurl', {
          credentials: 'include',
          headers: myHeaders,
          method: 'GET'
      }).then( res => {
      
          return res.json();
      
      }).then( res => {
      
          /**your stuff*/
          
      });
      

      然后在您的服务器中检查标头,您将看到 Bearer

      【讨论】:

      • 我认为这个答案是有效的,但它缺少“如何”。在 expressjs 内部,您可以 res.send("your token here") 好吧,但是一旦发送,客户端会将其作为 json 文件接收(特别是如果您想发送其他用户信息,例如姓名或电子邮件)。好的,现在,在客户端,客户端如何将令牌设置为标头?因为例如,要访问仪表板,用户将需要身份验证,令牌必须在标题中。怎么样?
      猜你喜欢
      • 1970-01-01
      • 2016-04-05
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多