【问题标题】:Using middleware to call an Authentication API using ExpressJS使用中间件使用 ExpressJS 调用身份验证 API
【发布时间】:2015-06-15 16:00:46
【问题描述】:

我正在使用两个 Node.js + Express 应用程序:

  • 后端
  • 身份验证

我的前端是用 AngularJS 构建的

基本上,我尝试将 json Web 令牌与每个请求一起发送到后端,然后使用路由中间件来调用身份验证 API。它验证该令牌并将用户数据添加到请求中。最后,我使用用户数据在后端处理请求以获取我的资源。

var app = angular.module('myApp', [<dependencies>
]).config(function ($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/login.html'
        })
        .when('/foo', {
            templateUrl: 'views/foo.html'
        })
        .otherwise({
            templateUrl: '404.html'
        });

    $locationProvider.html5Mode({
        enabled: false,
        requireBase: false
    });

    $httpProvider.interceptors.push(['$q', '$location', '$sessionStorage', function($q, $location, $sessionStorage) {
        return {
            'request': function (config) {
                config.headers = config.headers || {};
                if ($sessionStorage.token) {
                    config.headers.Authorization = $sessionStorage.token;
                }
                return config;
            },
            'responseError': function (response) {
                if (response.status === 401 || response.status === 403) {
                    $location.path('/');
                }
                return $q.reject(response);
            }
        };
    }]);
});

然后,我在后端的中间件处理程序如下所示:

var router = express.Router(); 
// middleware to use for all requests
router.use(function (req, res, next) {
    'use strict';
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    next(); 
});

//middleware to validate token
router.use('/foos', function (req, res, next) {
    'use strict';
    var token = req.headers.authorization;
    console.log(token);
    authorizeRequest(token);
    next();
});

router.get('/foos', function (req, res) {
    'use strict';
    actividadController.getActividad(req, res);

});

app.use('/api', router);

app.listen(8080);

authorizeRequest 函数调用 Authentication API。

我的问题是每个请求都会调用两个中间件两次,但我找不到发生这种情况的原因。

【问题讨论】:

  • 当您查看浏览器的网络活动时,您是否看到请求被触发了两次?
  • 我看到一个用 GET 调用,另一个用 OPTIONS 调用,也许这就是中间件被触发两次的原因,对吧?
  • 完全正确。我已经发布了一个答案,详细说明了我将如何解决这个问题。希望对您有所帮助!

标签: angularjs node.js authentication express


【解决方案1】:

看起来中间件是从OPTIONS 请求中触发的。使用像 cors 这样更强大的 express 库将解决这个问题。

或者,您可以手动检查OPTIONS 请求,然后返回必要的信息而不是调用next(),但除非您确切知道自己在做什么,否则我不建议这样做。

祝你好运!

【讨论】:

    【解决方案2】:

    最后我用http方法代替了url。

    我使用的是路由器,而不是 router.use。和一个描述 uri 的正则表达式。

    router.get('/user/:username/*', function (req, res, next) {
        'use strict';
        var token = req.headers.authorization;
        http.get('http://localhost:10020/api/tokens/' + token, function (response) {
            if (response.statusCode === 200) {
                next();
            } else {
                res.status(response.statusCode).json({ message: "Rejected" });
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2020-05-03
      • 2015-12-07
      相关资源
      最近更新 更多