Login by facebook in angular app with loopback backend

这一生的挚爱 提交于 2019-12-03 12:11:01

问题


I'm making an angular application with strongloop loopback backend.

Also I integrating a third party login by facebook using loopback-passport module.

everything was fine in loopback-example-passport and everything is fine in my app right before the moment of redirecting to my app. User and Access-token created.

the code:

app.get('/auth/login', ensureLoggedIn('/#login'), function(req, res, next) {
    console.log('LOOGED IN!!');
console.log(req.user);

  res.redirect('/#auth/login');
});

works fine. But i can't understand. how to give authenticated state to my angular application.

i tried to make a controller to route '/#auth/login':

.controller('AuthCalbackCtrl', function($scope, $cookies, $location, AppAuth, $http, User, LoopBackAuth) {
//analogue of User.login responce interceptor
   LoopBackAuth.currentUserId = $cookies['userId'] || null;
   LoopBackAuth.accessTokenId = $cookies['access-token'] || '';
   LoopBackAuth.rememberMe = false;
   LoopBackAuth.save();
   //asking for currentUser
   User.getCurrent(function(user) {
     console.log('ser.getCurrent ', user);
   });
   $location.path('/');
  })

This code makes a request GET /api/users/2 but receives 401 error.

If I tweak the file /loopback/lob/models/user.js setting permission:

  principalType: ACL.ROLE,
  // principalId: Role.OWNER,
  principalId: Role.EVERYONE,
  permission: ACL.ALLOW,
  property: "findById"

Then the request GET /api/users/2 receives 200 and everything ok.

I'm a little confused. I can`t understand how to make my angular app authenticate to loopback, although i know access-token and userId

Have anybody any ideas how to do it?


回答1:


Here is a valid code.

app.get('/auth/login', function(req, res, next) {
  //workaround for loopback-password 
  //without this angular-loopback would make incorrect authorization header
  res.cookie('access-token', req.signedCookies['access-token']);
  res.cookie('userId', req.user.id);
  res.redirect('/#auth/login');
});

The problem is that loopback-passport signs cookie:

         res.cookie('access-token', info.accessToken.id, { signed: true,
           maxAge: info.accessToken.ttl });

In string it looks something like the following "s:.eBvo8bpo9Q9wnNrPjjlG%2FAcYqWkxEgNFqn%2FO54rdGwY"

But loopback-angular just copies the access-token to header.authorization, so we need to put there plain cookie.



来源:https://stackoverflow.com/questions/24213792/login-by-facebook-in-angular-app-with-loopback-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!