Angular 使用 Passport for Ionic App 进行身份验证
Angular authentication using Passport for Ionic App
我已经为我的网络应用构建了一个 API,它是使用 MEAN 堆栈构建的。
现在我正在尝试在使用 Ionic Framework 构建的移动客户端上使用此 API。
我正在使用此代码对 API:
执行 $http 调用
$http.post(ServerIP+'/login', {username: $scope.credentials.username, password: $scope.credentials.password}).success(function(response) {
$scope.authentication.user = response;
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
它得到了用户对象的有效响应,但是如果我尝试从 API 的受保护部分获取一些信息,它不起作用并且正在重置身份验证。
在网络应用程序上,我使用相同的代码并且一切正常。
此问题仅发生在 Ionic 应用程序上。
我已经这样设置了 CORS:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.sendStatus(200);
}
else {
next();
}
});
请帮帮我!
尝试在您的 angular 配置中添加此行:
app.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
});
我已经通过添加基于令牌的身份验证解决了这个问题。
这篇文章展示了如何做到这一点:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
我的 "login" 路线示例:
router.post('/login', passport.authenticate('local'), function(req, res, next){
if (req.user) {
var token = jwt.sign(req.user, secret, {expireInMinutes: 60*24*7});
res.json(token);
};
});
为了在受保护的路由上获取用户对象,我正在使用 expressJwt({secret: secret})
中间件。
我已经为我的网络应用构建了一个 API,它是使用 MEAN 堆栈构建的。 现在我正在尝试在使用 Ionic Framework 构建的移动客户端上使用此 API。 我正在使用此代码对 API:
执行 $http 调用 $http.post(ServerIP+'/login', {username: $scope.credentials.username, password: $scope.credentials.password}).success(function(response) {
$scope.authentication.user = response;
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
它得到了用户对象的有效响应,但是如果我尝试从 API 的受保护部分获取一些信息,它不起作用并且正在重置身份验证。
在网络应用程序上,我使用相同的代码并且一切正常。 此问题仅发生在 Ionic 应用程序上。 我已经这样设置了 CORS:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.sendStatus(200);
}
else {
next();
}
});
请帮帮我!
尝试在您的 angular 配置中添加此行:
app.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
});
我已经通过添加基于令牌的身份验证解决了这个问题。
这篇文章展示了如何做到这一点:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
我的 "login" 路线示例:
router.post('/login', passport.authenticate('local'), function(req, res, next){
if (req.user) {
var token = jwt.sign(req.user, secret, {expireInMinutes: 60*24*7});
res.json(token);
};
});
为了在受保护的路由上获取用户对象,我正在使用 expressJwt({secret: secret})
中间件。