在开始之前,我的问题与此问题非常相似:passport object empty not getting called in passport/express app, not calling deserializeUser
但即使他的修复对我来说也没有用(陈词滥调,我知道)。通常我是一直在浏览互联网的人,直到我找到解决方案,这次我找不到它,所以我转向你们寻求帮助:-)让我们开始吧:
我正在使用2个单独的域/服务器,1个用于角度应用程序(向另一个域发出请求),1个用于基于Node / Express的API。我的Angular应用程序在localhost:8081上运行(使用节点包http-server),我的API在localhost:8080上运行。
CORS-设置
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8081");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP- Method-Override, Content-type, Accept, X-Access-Token, X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
console.log(req.headers); });
Server.js
mongoose.connect(configDB.url);
require('./config/passport')(passport);
app.use(morgan('dev'));
app.use(cookieParser('secret'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
name: 'passportSessionName',
secret: 'secret',
resave: false,
saveUninitialized: false,
unset: 'keep',
cookie: {
domain: 'localhost',
maxAge: 1000 * 60 * 60 * 24 * 30 // 30 days
} ,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
app.use(passport.initialize());
app.use(passport.session());
require('./routes/routes.js')(app, passport);
Angular Snipps
.factory('TokenInterceptor', function($q, $window) {
return {
request: function(config) {
console.log("HEADERTOKEN: " + $window.sessionStorage.token);
console.log("HEADERKEY: " + $window.sessionStorage.userid);
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['x-access-token'] = $window.sessionStorage.token;
config.headers['x-key'] = $window.sessionStorage.userid;
config.headers['Content-Type'] = "application/json";
}
return config || $q.when(config);
},
response: function(response) {
return response || $q.when(response);
}
};
})
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('TokenInterceptor');
}]);
问题:如果我登录,everthing工作正常,直到我发出新的GET请求,服务器端的passport-object为空(并且deserializeUser永远不会被调用)。另外要知道的是x-access-token和x-key在服务器端接收得很好。
HEADERTOKEN: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzM3NjA1NDk3NDN9.I-1DvM4xP6PyNKWEQvcWkWKorXTzYCB5IJvzygm80pk
HEADERKEY: 55690d01d8f4cf5827000001
{ host: 'localhost:8080',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:8081',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36',
'x-access-token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzM3NjA1NDk3NDN9.I-1DvM4xP6PyNKWEQvcWkWKorXTzYCB5IJvzygm80pk',
'x-key': '55690d01d8f4cf5827000001',
referer: 'http://localhost:8081/search',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4',
cookie: 'connect.sid=s%3A0vhuShzqfR1RDk0Ut4LNpA-g8W4xiwkC.lC4QIl%2FcNoOuWNQAyYjtkuqD3NTUTSZx0GxCtzf0hVI; sessionObject=%7B%22token%22%3A%22%242a%2408%247OfU9Ptri6WLYu0essB5KOyoeNYFqtYSpbUBW8wDt21Sc9
hECcPQi%22%2C%22email%22%3A%22t@t.be%22%2C%22logintype%22%3A%22local%22%2C%22userid%22%3A%2255690d01d8f4cf5827000001%22%2C%22name%22%3A%22test%22%2C%22role%22%3A%22user%22%2C%22avatar%22%3A%22http%3A/
/www.dapi.be/L2693.gif%22%7D' }
{ cookie:
{ path: '/',
_expires: Wed Jul 01 2015 12:49:13 GMT+0200 (Romance (zomertijd)),
originalMaxAge: 2592000000,
httpOnly: true,
domain: 'localhost' },
passport: {} }
实际上有什么用处:当我使用Postman执行这些请求时,everthing工作正常,并且everthing被称为应该的方式。
所以我猜问题在于CORS标题,但我无法弄清楚它是什么。
更新(config / passports.js)
passport.serializeUser(function(user, done) {
console.log("serializeUser:" + user);
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log("deserializeUser:" + id); // THIS DOESNT GET CALLED WITH ANGULAR
User.findById(id, function(err, user) {
if (!err) done(null, user);
else done(err, null);
});
});
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, email, password, done) {
if (email)
email = email.toLowerCase();
// asynchronous
process.nextTick(function() {
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, { error: 'No one found by this email. ' });
if (!user.validPassword(password))
return done(null, { error: 'Oops! Wrong password.' });
// all is well, return user
else
return done(null, user);
});
});
}));