Reputation: 4128
I'm working on an application which is mostly CRUD based. It's written in PHP and exposes itself out through a JSON API.
The front end is being written in AngularJS and I'm getting to the stage where I need to sort out authentication. I know I want it to be token based, and preferably it should be able to simply login with Facebook.
Since all the data etc is on the PHP backend, I assume that is where the authentication should take place. My idea is to have the AngularJS front end ask the PHP backend to login, at which point the backend goes off and logs in with facebook, saves away the token in the database, and sends it back to the AngularJS frontend so that it can provide it with subsequent requests.
Where I am a bit stuck is getting AngularJS to ask the backend to authenticate. What's the best way to handle that? Should I simply have a link on the frontend that does an http request to the backend? But if I do that, how does the user ever get presented the login with facebook dialogue.
Let's assume my frontend is http://front.myapp.com and the backend is http://back.myapp.com then the authentication is handled at something like http://back.myapp.com/auth
My question is, what kind of code would I write on the AngularJS side to get it to properly talk with the backend, considering that the backend also has to go off and talk to facebook? Real code examples would be the most helpful.
Upvotes: 3
Views: 1339
Reputation: 709
I advice you to use this library http://jberta93.github.io/ng-facebook-api/ and do the Facebook auth on your frontend. You can easily retrive user data and then with $http.post you can submit this data to your backend app! Then if you need to talk with backend with Facebook you can use the authResponse returned from library in frontend authentication! In this way in your app domains you specify only the frontend url. And your user doesn't see the backend app!
A little example:
$scope.logAndRetriveFacebookUser = function(){
facebook.getUser().then(function(r){
var user = r.user; //User data returned;
var authResponse = r.authResponse; //Token auth, id etc..
$http.post('/backend-login-url', {user:user,authResponse:authResponse});
}, function(err){
console.log("Ops, something went wrong...");
});
}
Upvotes: 2