使用Passport for Ionic App进行角度身份验证

时间:2015-06-03 21:13:54

标签: angularjs node.js ionic-framework ionic mean-stack

我为我的网络应用程序构建了一个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的受保护部分获取一些信息,它就不起作用,并且auth正在被重置。

在网络应用上,我使用相同的代码,一切正常。 此问题仅在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();
 }
});

拜托,帮助我!

2 个答案:

答案 0 :(得分:0)

尝试在角度配置中添加此行:

app.config(function ($httpProvider) {
    $httpProvider.defaults.withCredentials = true;
});

答案 1 :(得分:0)

我通过添加基于令牌的身份验证解决了这个问题。

以下是介绍如何执行此操作的文章:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

我的“登录”路线示例:

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})中间件。

相关问题