How can I implement the facebook authentication in

2019-09-11 19:16发布

问题:

I'm implementing an application using the full MEAN stack. I created a login page to signup with facebook to be able to show a profile page. But I discovered some problems. For this reason, I created a smaller version of my webapp, maintaining the same project structure. The complete code, executable (only replacing "client id" and "secret") with "npm install" and after "nodemon" is available here: https://github.com/Ks89/MEAN-OAuth_Example

If I'll call (with a browser) the rest API that I created to login with facebook at "http://localhost:3000/api/auth/facebook", everything will be ok! But if I'll want to do the same thing, clicking on the "Login" button, I'll receive the error as in figure:

I know that the problem is related to CORS, but how can I'll fix this in my application, maintaining the same project structure? I don't want to put the "rest path" inside the HTML. I tried for many days different solutions without success.

If you want, experiment directly on my application that I created exactly to write this question ;).

If really necessary, I'll able to post the entire source code here, but I prefer an organized and executable code into a repository for this particular question.

Please, give me some ideas and hopefully a solution, because I'm really blocked.

回答1:

The example routes from the passport-facebook repo are intended for multipage apps, not ajax requests. If you look at what those routes are doing, /auth/facebook is just a redirect to Facebook where the user is expected to log in if necessary and authorize your application. When you make that same request from angular, it follows the redirect and tries to load the Facebook page, but the browser blocks you as your console screenshot shows. CORS would be relevant if Facebook wanted to allow you to request their login form across origins, but they don't because that would basically make you a phisher.

It looks like you're trying to handle authentication without leaving the page, but at some point you're going to need the user to leave your site and be redirected to Facebook in order to complete the OAuth flow. You can either open a pop-up containing the Facebook OAuth dialog (it looks like this is what the Facebook JavaScript SDK does by default) or just use your app's current tab with something as simple as <a ng-href="{{facebookOauthUrl}}">Log in with Facebook</a>.