How can I implement the facebook authentication in a MEAN application preventing CORS problems?

…衆ロ難τιáo~ 提交于 2019-12-13 04:01:01

问题


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>.



来源:https://stackoverflow.com/questions/34755424/how-can-i-implement-the-facebook-authentication-in-a-mean-application-preventing

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