我正在创建一个网站,我正在处理登录详细信息。
我正在使用Passport插件来提供一个完整的应用程序,但每次我尝试登录时,无论我做什么都会得到“未经授权”。
登录控制器
$scope.login = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.login({
email: $scope.user.email,
password: $scope.user.password,
})
.then( function() {
// Logged in, redirect to home
$location.path('/');
})
.catch( function(err) {
$scope.errors.other = err.message;
console.log(err);
});
}
};
AUTH SERVICE
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/local', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
SERVERSIDE INDEX.JS
'use strict';
var express = require('express');
var passport = require('passport');
var auth = require('../auth.service');
var router = express.Router();
router.post('/', function(req, res, next) {
passport.authenticate('local', function (err, user, info) {
var error = err || info;
if (error) return res.json(401, error);
if (!user) return res.json(404, {message: 'Something went wrong, please try again.'});
var token = auth.signToken(user._id, user.role);
res.json({token: token});
})(req, res, next)
});
module.exports = router;
我对护照插件比较新,所以我不知道在哪里可以找到错误。如果您需要更多代码,请告诉我。
这是我从控制台收到的消息:
Failed to load resource: the server responded with a status of 401 (Unauthorized) angular.js:9866
GET http://localhost:9000/api/users/me 401 (Unauthorized)
答案 0 :(得分:-1)
发现问题
我错过了一些代码。我不知道为什么,但我做到了。问题已经解决了。
app.js中缺少的代码:
.factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if(response.status === 401) {
$location.path('/login');
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$stateChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
$location.path('/login');
}
});
});
});