Facebook server-side login, CORS

孤街浪徒 提交于 2021-02-10 12:49:41

问题


I'm implementing a web site with FB server-side login as simplified steps below:

  1. A simple button triggers JS script which calls my backend API https://localhost/fblogin

    function sendFbLoginData() {
        $.get("https://localhost/fblogin", function(data, status) {});
    }
    
  2. In the backend handler of /fblogin the user is redirected to FB login dialog for requesting permissions and access token.

    func (ct *LoginController) FbLogin() {
        url := "https://www.facebook.com/dialog/oauth?client_id=xxx&redirect_uri=https://localhost/fboauth2cb&response_type=code&scope=public_profile"
        ct.Redirect(url, 302)
        return
    }
    
  3. At browser console shows error msg:

    XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?client_id=xxx&redirect_ur…e_type=code&scope=public_profile. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.
    

After googling I realize this is a CORS problem. Since I cannot change Facebook's behavior, how do I deal with this problem? or fundamentally I do fb server-side login in a wrong way?

ps. my env is AWS + Beego (golang)


回答1:


You cannot ask for https://www.facebook.com/dialog/oauth?... from JavaScript and wait for its results; that page is intended to be shown in a browser, so that Facebook can ask the user for its credentials and permission to use his account in your app.

So, instead of:

    $.get("https://localhost/fblogin", function(data, status) {});

you should use something like:

    location = "https://localhost/fblogin";



回答2:


in your app settings in Facebook in settings tab (somewhere like https://developers.facebook.com/apps/{app-id}/settings/)you should set your site URL to https://localhost/ so it can recognize it as a valid redirect



来源:https://stackoverflow.com/questions/27716212/facebook-server-side-login-cors

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