我使用护照本地护照进行mongoDB登录。
passport.use('local-login', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback : true
},
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
console.log(user);
console.log(req.session);
console.log(req.session.passport);
return done(null, user);
});
}
));
和POST电话
router.post('/login', passport.authenticate('local-login'), function(req, res) {
res.json(req.user);
});
当我从角度会话进行POST调用时没有得到保存。这是来自角度POST请求后服务器的我的console.log:
-------user---------
{ _id: 5782f005917d7fa01b27adba,
username: 'asd',
password: 'asd',
__v: 0,
roles: [ 'user' ] }
-------req.session---------
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: false } }
-------req.session.passport---------
undefined
----------------
serializeUser: 5782f005917d7fa01b27adba
我也和邮递员一起测试了它似乎正在工作。登录apear会话后的用户:
-------req.session---------
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: false },
passport: { user: '5782f005917d7fa01b27adba' } }
-------req.session.passport---------
{ user: '5782f005917d7fa01b27adba' }
我的配置是:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(session({
secret: 'brucespringsteinmegaboss',
resave: true,
saveUninitialized: true,
cookie: {
secure: false
} }));
app.use(passport.initialize());
app.use(passport.session());
包:
"body-parser": "^1.15.2",
"express": "^4.14.0",
"express-session": "^1.14.0",
"mongoose": "^4.5.3",
"passport": "^0.3.2",
"passport-local": "^1.0.0"
npm:3.9.6 节点:6.2.2
角度呼叫:
$scope.login = function(form, user) {
if (form.$valid) {
$http.post('http://localhost:3000/api/auth/local/login', user)
.success(function(resp){
$rootScope.currentUser = user;
console.log($rootScope.currentUser);
});
}
};
如果有人解释这个问题,我将不胜感激。
答案 0 :(得分:0)
我在角度方面用withCredentials: true,
解决它
app.js上的
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:9000');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept");
});