Facebook server-side login, CORS

2019-07-22 02:30发布

问题:

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:

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



回答2:

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";