0

问题:Satellizer 没有向服务器发送授权标头。

我正在我正在从事的项目中试用 Satellizer.Js。到目前为止这很好,但是,它没有正确地将请求中的授权标头发送到服务器(注意:我使用 Node 作为后端)。这不是 CORS 问题,因为我目前正在使用 localhost。当我在本地登录/注册时,服务器会使用令牌进行响应,Satellizer 会在本地存储中正确设置该令牌。我检查了开发工具中的 Network 选项卡以检查标头,但没有 Authorization 标头。有没有人处理过这个问题,或者有什么我可以使用的想法/技巧?提前致谢。

这是我的 server.js 代码:

var express = require('express'),
app = express(),
path = require('path'),
cors = require('cors'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
config = require('./config/config'),
morgan = require('morgan'),
port = process.env.PORT || 8080;


var express = require('express'),
app = express(),
path = require('path'),
cors = require('cors'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
config = require('./config/config'),
morgan = require('morgan'),
port = process.env.PORT || 8080;


//connect to the database
mongoose.connect(config.db);
//morgan - log all requests to the console
app.use(morgan('dev'));

//middleware for body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

//handle CORS requests
app.use(cors());
/*app.use(function(req,res,next){
   res.setHeader('Access-Control-Allow-Origin', '*');
   res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
   res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, \ Authorization');  
   next();
});*/

//set the location for static files
app.use(express.static(__dirname + '/public'));

//API Routes
var apiRoutes = require('./app/routes/app-routes.js')(app,express);

app.use('/auth', apiRoutes);

//send the users to the front end
app.get('*', function(req,res){
   res.sendFile(path.join(__dirname + '/public/app/views/index.html')); 
});


//listen on port
app.listen(port, function(){
   console.log('Listening on port: ' + port + "...."); 
});

这是使用卫星器在角度侧设置令牌的位置:

vm.login = function(){
        $auth.login({email: vm.user.email, password: vm.user.password})
            .then(function(res){                    
                //check for token;
                if(!res.data.token){
                    vm.error = true;
                    vm.errorMessage = res.data.message;
                }else{
                    //redirect to the dashboard

                    $location.path('/dashboard');
                }    
            })
            .catch(function(){
                vm.error = true;
                vm.errorMessage = "Failed to login, please try again."
            });
    };

这是我唯一经过身份验证的路线:

router.get('/dashboard', ensureAuthenticated, function(req,res){
    //with a validated token
    console.log(req.headers);
    console.log(req.headers.authorization);
    res.json({success: true, message:'You made it, congrats!'});
});

这是我的 create-a-token 函数,这是我的身份验证中间件:

function createToken(user){
    var payload = {
        exp: moment().add(14, 'days').unix,  
        iat: moment().unix(),
        sub: user._id
    }
    return jwt.encode(payload,config.secret);
};

function ensureAuthenticated(req, res, next) {
          if (!req.headers.authorization) {
            return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
          }
          var token = req.headers.authorization.split(' ')[1];

          var payload = null;
          try {
            payload = jwt.decode(token, config.secret);
          }
          catch (err) {
            return res.status(401).send({ message: err.message });
          }

          if (payload.exp <= moment().unix()) {
            return res.status(401).send({ message: 'Token has expired' });
          }
          req.user = payload.sub;
          next();
    }

注意:Satellizer.Js 的 $httpInterceptor 负责发送请求中的令牌。这是该代码:

.factory('SatellizerInterceptor', [
  '$q',
  'SatellizerConfig',
  'SatellizerStorage',
  'SatellizerShared',
  function($q, config, storage, shared) {
    return {
      request: function(request) {
        if (request.skipAuthorization) {
          return request;
        }

        if (shared.isAuthenticated() && config.httpInterceptor(request)) {
          var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
          var token = storage.get(tokenName);

          if (config.authHeader && config.authToken) {
            token = config.authToken + ' ' + token;
          }

          request.headers[config.authHeader] = token;
        }

        return request;
      },
      responseError: function(response) {
        return $q.reject(response);
      }
    };
  }])
.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('SatellizerInterceptor');
}]);
4

3 回答 3

0

token你手动设置的动机是什么,当使用$auth.setTokenSatellizer自动处理它$auth.login

这是Satellizer在我们的应用程序中完美运行的登录示例:

angular.module('MyApp')
  .controller('LoginCtrl', function($scope, $location, $auth, toastr) {
    $scope.login = function() {
      $auth.login($scope.user)
        .then(function() {
          toastr.success('You have successfully signed in!');
          $location.path('/');
        })
        .catch(function(error) {
          toastr.error(error);
        });
    };
  });

底线:你不应该设置token自己。 Satellizer它会在幕后自动完成。

于 2016-01-18T19:49:04.387 回答
0

尝试像这样设置授权标头...

request.headers.Authorization = token;
于 2016-01-18T17:56:33.007 回答
0

我有同样的问题。您必须发送带有“/api/”前缀的所有请求。没有这个前缀我得到了错误,但是 w

于 2016-12-03T21:55:05.907 回答