为什么授权标头在MEAN应用程序

时间:2016-04-14 08:58:38

标签: angularjs node.js express jwt

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

我的场景是我存储了存储在本地存储中的身份验证令牌,当授权令牌可用时,它会考虑经过身份验证的用户并允许访问URL以及何时令牌不可用。

所以我使用了角度拦截器在每个请求中添加了Authorization标头。它确实添加了每个请求,但我无法从服务器端获取。在每个请求中,我都传递了Authorization标头,但它总是返回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,但为什么不返回我不知道的标题值。

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
  

浏览器控制台响应

enter image description here

0 个答案:

没有答案