我是第一次设置身份验证功能,在用户登录后我得到了一些意想不到的结果。一位同事给了我一个具有工作身份验证的应用程序来模拟我的应用程序,它似乎是我拥有的一切完成是正确的。
我在前端使用 AngularJS,SailsJS 后端框架,并且 PassportJS认证中间件。
我的源代码(目前)是公开存储的...后端 API 位于 Github 此处 (API Github),前端代码位于此处 (Front-End Github)
基本上发生的是用户
点击登录按钮,触发此功能
login: function (credentials) { return baseAuth.customPOST(credentials, 'login').then(function (user) { $log.debug('User logged in: ', user); isAuthenticated = true; return user; }); },
customPOST 的 Controller 逻辑是这样的
login: function (req, res, next) { passport.authenticate('local', function (err, user, info) { if (err) { return res.json(err); } else if (user) { req.logIn(user, function (err) { if (err) { return res.json(err); } return res.json(user); }); } else { return res.json(400, info); } })(req, res); },
在那一步中,护照应该做它的事情并登录用户
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function(email, password, next) { User.findOne({ email: email }) .exec(function (err, user) { if (err) { return next(err); } if (user) { if (user.activated) { bcrypt.compare(password, user.password, function (err, valid) { if (err) { next(err); } if (valid) { return next(null, user, { message: 'Logged In' }); } else { return next(null, false, { message: 'Incorrect password'}); } }); } else { next(null, false, { message: 'User is not activated. Please contact admins.'}); } } else { next(null, false, { message: 'Could not find user with email ' + email }); } }); } ));
在控制台中,我总是知道这是成功的。
控制台读取:
User logged in: Object {firstName: "John", lastName: "Doe", email: "john_doe@work.com", activated: true, isUser: true…}
然后,我对发生的事情的理解变得有点模糊。我知道应用程序然后会尝试查看用户是否已通过身份验证。 IsAuthenticated 被触发,在 AngularJS 中看起来像这样:
isAuthenticated: function (force) { var deferred = $q.defer(); if (isAuthenticated && currentUser) { deferred.resolve(currentUser); } else { return baseAuth.customGET('authenticated').then(function (user) { deferred.resolve(currentUser); isAuthenticated = true; currentUser = user; return user; }); } return deferred.promise; }
它在后端 UserController 中命中此操作
isAuthenticated: function (req, res) { if (req.isAuthenticated() && req.user.isUser) { return res.json(req.user); } else { return res.send(401); } },
然后它失败了:( test 并且它们都不是真的。“isUser”是我默认为 true 的值,因此它应该对数据库中的每个用户都是 true。req.isAuthenticated 也失败了,我不完全理解。
有人了解我的问题吗?我在这里做错了什么?
最佳答案
如果您的前端应用程序与后端应用程序的来源不同the AJAX requests will not include the session cookie并且 req.isAuthenticated()
永远不会返回 true。
使用 withCredentials 选项强制执行。
$http({ withCredentials: true, ... })
Restangular 似乎使用相同的选项:
https://github.com/mgonto/restangular#setdefaulthttpfields
https://docs.angularjs.org/api/ng/service/$http#usage
编辑:您还应该检查 the server side configuration正如 idbehold 所指出的
正如 Matan 所建议的,您真的应该尝试在服务器端使用 sails-generate-auth 生成器。
关于angularjs - 身份验证不应该返回 "401 (Unauthorized)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082887/