为什么在MEAN应用程序的每个请求中授权头返回undefined

我使用JWT实现了身份validation。 在每个请求中,我想访问授权令牌,但是当我尝试访问它时总是返回undefined。

我的情况是,我存储了存储在本地存储中的身份validation令牌,当授权令牌可用时,它考虑已authentication的用户,并允许访问URL以及何时令牌不可用。

所以我使用angular拦截器在每个请求中添加授权标头。 它确实添加了每个请求,但我无法从服务器端获得。 在每个请求中,我传递授权标题,但它总是返回undefined作为输出。

请查看我的代码并提供指导。

app.route.js [AngularJS]

(function () { function authInterceptor($window) { return{ request: function (config) { if ($window.localStorage['hz-token']) { config.headers.Authorization = 'Bearer ' + $window.localStorage['hz-token']; } return config; } } } /* * Default Route of application * @param {$stateProvider} Object * @param {$routeProvider} Object * @return */ function config($stateProvider, $urlRouterProvider, $httpProvider) { $urlRouterProvider.otherwise('index'); $httpProvider.interceptors.push('authInterceptor'); $stateProvider .state('app', { url: '/', views: { 'globalHeaderLine1': {templateUrl: '/partials/headerLine1.html', controller: 'SigninCtrl', controllerAs: 'Signin'}, 'globalHeaderLine2': {templateUrl: '/partials/headerLine2.html'}, 'footer': {templateUrl: '/partials/footer.html'} } }) .state('app.index', { url: 'index', views: { 'globalHeaderLine3@': {templateUrl: '/partials/headerLine3.html'}, 'globalHeaderLine4@': {templateUrl: '/partials/headerLine4.html'}, 'globalHeaderLine5@': {templateUrl: '/partials/headerLine5.html'}, 'globalHeaderLine6@': {templateUrl: '/partials/headerLine6.html'}, 'globalHeaderLine7@': {templateUrl: '/partials/headerLine7.html'}, 'content@': {templateUrl: '/views/home/home.html', controller: 'HomeCtrl', controllerAs: 'Home'} } }) .state("app.resetpassword", { url: "resetpassword", views: { 'content@': {templateUrl: '/views/auth/resetpassword.html', controller: 'ResetPasswordCtrl', controllerAs: 'ResetPassword'} } }) .state('app.contactus', { url: 'contactus', views: { 'content@': {templateUrl: '/views/home/contactus.html', controller: 'ContactusCtrl', controllerAs: 'Contactus'} } }) .state('app.useractivation', { url: 'useractivation', views: { 'content@': {templateUrl: '/views/auth/useractivation.html', controller: 'UserActivationCtrl', controllerAs: 'UserActivation'} } }) } angular .module('AppAquireConsole') .factory('authInterceptor', ['$window', authInterceptor]) .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', config]) .run(function ($rootScope, $http, notifications, $location, UserService) { if ($location.path() === '/resetpassword' && ('' !== $location.search().q)) { $http({ method: "GET", url: '/api/user/resetPassword?forgotPasswordToken=' + $location.search().q }).success(function (data) { if (data.status === 0) { $location.path("#/"); notifications.showSuccess({ message: 'This token has been expired', hideDelay: 3000, //miliseconds hide: true // boolean }); } }); } }); }()); 

SignoutCtrl.js [AngulrJS]

 (function () { 'use strict' function SignoutCtrl($scope, $location, $window, $rootScope, UserService) { $scope.isAuth = UserService.isLoggedIn(); $scope.doLogout = function () { //JSON.parse(localStorage.getItem("CurrentUserData")); //localStorage.removeItem("CurrentUserData"); UserService.logOut(); $rootScope.$broadcast('unauthorized'); $window.location.reload(); } } angular .module('AppAquireConsole') .controller('SignoutCtrl', ['$scope', '$location', '$window', '$rootScope', 'UserService', SignoutCtrl]); }()); 

Config.js:我定义了允许在nodejs中访问Authoraization,但为什么不返回我不知道的Header值。

 var express = require("express"); var http = require("http"); var path = require("path"); var bodyParser = require("body-parser"); var cookieParser = require("cookie-parser"); var expressSession = require("express-session"); var methodOverride = require("method-override"); var morgan = require("morgan"); var passport = require("passport"); var randToken = require('rand-token'); var jwt = require("jsonwebtoken"); //var mongoose = require("mongoose"); var app = express(); //MongoDB //============================================================================= require("./db"); //Application configuration variables // ============================================================================= app.set("port", process.env.PORT || 1000); app.set("env", "development"); //Set JWT Private Key //============================================================================= process.env['JWT_PRIVATE_KEY'] = randToken.generate(64); //Set Process environment variables //============================================================================= process.env['RECAPTCHA_PRIVATE_KEY'] = ***** RECAPTCHA PRIVATE KEY *****; app.enable('trust proxy'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cookieParser()); // Express Session app.use(expressSession({ secret: 'cookie_secret', name: 'cookie_name', proxy: true, resave: true, saveUninitialized: true })); // Passport Init app.use(passport.initialize()); app.use(passport.session()); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT app.use(methodOverride('X-HTTP-Method-Override')); //Serving Static Direcotries //============================================================================= require("./utils")(express, app, path); app.all('/*', function (req, res, next) { console.log(req.headers); // CORS headers res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // Set custom headers for CORS res.header('Access-Control-Allow-Headers', 'Content-type,Accept,Authorization'); console.log(" :::: Content-type :::: "); console.log(req.headers['Content-type']); if (req.method === 'OPTIONS') { res.status(200).end(); } else { next(); } }); //Routes //============================================================================= // Application Routes var router = express.Router(); //Default routes executes in every request router.use(function (req, res, next) { //res.json({message: "AquireConsole default routing executed"}); var token; if (req) { // In a separate `if` because it is common to all the tests if (req.body && req.body.token) { token = req.body.token; } else if (req.query && req.query.token) { token = req.query.token; } else if (req.headers && req.headers['Authorization']) { token = req.headers['Authorization']; } } console.log(" :::: Authorization :::: "); console.log(token); next(); }); // router.get("#/", function (req, res) { // res.sendFile(basePath + "bin/client/app/views/index.html"); // }); app.use(require('../app/data/routes/user')); router.get("*", function (req, res) { res.sendFile(basePath + "app/client/views/index.html"); }); app.use("*", router); //Error handlers //============================================================================= //Development error handler will print stacktrace if (app.get('env') === "development") { router.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } //Error handlers: no statistics leaked to user router.use(function (err, req, res, next) { res.status(err.status || 500); // res.render('error', { // message: err.message, // error: {} // }); }); //Instantiation of app //============================================================================= http.createServer(app).listen(app.get('port'), function () { console.log('AquireConsole is listening on port ' + app.get('port')); }); // expose app exports = module.exports = app; 

User.js [Express]

 router .route("/api/user/logout") .post( function (req, res, next) { req.logout(); res.json({status: 1, message: "Session windup"}); } ); 

NodeJS控制台响应

 { host: 'localhost:1000', 'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:44.0) Gecko/20100101 Firefox/44.0', accept: 'image/png,image/*;q=0.8,*/*;q=0.5', 'accept-language': 'en-US,en;q=0.5', 'accept-encoding': 'gzip, deflate', referer: 'http://localhost:1000/css/style.css', cookie: 'cookie_name=s%3A94jdWCuOndbOnuR3jncf37yHkXPCJomq.Ye8aX%2B7xMio9amQ79QENe0wrLBykvUF4N43rfQs4cpU', connection: 'keep-alive', 'cache-control': 'max-age=0' } :::: Content-type :::: undefined :::: Authorization :::: undefined 

浏览器控制台响应

在这里输入图像描述

       

网上收集的解决方案 "为什么在MEAN应用程序的每个请求中授权头返回undefined"