从浏览器发送http请求时缺少授权标头

时间:2016-09-07 18:59:34

标签: javascript node.js http express authorization

我在nodejs中有一个带有jwt授权的应用程序,当我从posman发送get时,发现了身份验证头,但是当我从浏览器发送它时,缺少授权头。 这是节点代码,我试图在verifyToken方法中获取授权头,但不在那里:

'use strict';

var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var _ = require('lodash');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens

var config = {
  appRoot: __dirname // required config
};

app.set('superSecret', config.secret); // secret variable
// bootstrap database connection and save it in express context
app.set("models", require("./api/model"));
var a = app.get("models").Role;

var repositoryFactory = require("./api/repository/RepositoryFactory").init(app);

var verifyToken = function (req, res, next) {
  // verify token and read user from DB
  // var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiTm9tYnJlVXN1YXJpbyI6ImQiLCJQYXNzd29yZCI6IiQyYSQxMCRYS3BJM2ZDRVFoSzVKUFBQWEdIVVZPbUVPQTZsRVRoZDRtWHl4a0tDeGtUcEhvY0U0UTNILiIsImNyZWF0ZWRBdCI6IjIwMTYtMDktMDVUMTg6Mjk6MTYuMDAwWiIsInVwZGF0ZWRBdCI6IjIwMTYtMDktMDVUMTg6Mjk6MTYuMDAwWiIsInByb2Zlc2lvbmFsSWQiOm51bGwsInByb2Zlc2lvbmFsIjpudWxsLCJpYXQiOjE0NzMyNTczMjcsImV4cCI6MTQ3MzI5MzMyN30.CKB-GiuvwJsDAVnKsWb1FktI9tJY57lSgPRVEfW3pts';
  var token = req.headers.authorization;
  jwt.verify(token, 'shhhhh', function (err, decoded) {
    if (err) {
      res.status(403).json({ success: false, message: 'Failed to authenticate token.' });
    } else {
      // if everything is good, save to request for use in other routes
      req.user = decoded;
      next();
    }
  });
};

SwaggerExpress.create(config, function (err, swaggerExpress) {
  if (err) { throw err; }

  app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-CSRF-Token, X-Requested-With, Origin, client-security-token, X-Requested-With, Content-Type, Accept, Authorization");
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

  app.use(verifyToken);

  // install middleware
  swaggerExpress.register(app);



  var port = process.env.PORT || 10010;
  app.listen(port);
});

我不知道我缺少什么配置。

4 个答案:

答案 0 :(得分:0)

您需要在浏览器中设置这些标头,尝试使用名为ModHeader https://chrome.google.com/webstore/detail/modheader/idgpnmonknjnojddfkpgkljpfnnfcklj

的Chrome插件

答案 1 :(得分:0)

我认为如果您可以更改 verifyToken 功能中的代码会更容易:var token = req.headers.authorization;成为var token = req.headers.authorization || req.query.access_token || req.body.access_token;

因此,在浏览器中,您可以在“access_token”查询参数中添加令牌,以在服务器中进行身份验证,而不是设置标头。

希望它对你有所帮助!

答案 2 :(得分:0)

问题是我试图从OPTIONS方法获取授权令牌,这个方法是在实际的get,port,put等之前发送的,当时是CORS请求。所以我试图从它获取授权标题,它不存在,方法失败。 解决方案是在验证令牌方法中设置如下验证:

if (req.method !== OPTIONS){
}

答案 3 :(得分:0)

尝试在.htaccess中添加以下代码。 Apache删除授权标头。这将确保它不会被删除。

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1