Handling server redirect to Facebook login page in AngularJS

陌路散爱 提交于 2019-12-10 22:09:46

问题


I have an AngularJS app, and a WebApi2 with ASP.NET Identity 2.0. I am trying to log user in using Facebook account.

I am using this answer to do it.

Getting auth providers is easy, I have problem with the next step. It says, I should make GET request to my WebApi server, using the Url provided before. So I make my call and get a HTTP 302 with Location header set to facebook's login page.

The browser doesn't redirect, however. In Developer Tools I see that GET request to this address is made, but then in console there is

XMLHttpRequest cannot load [url here]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' therefore not allowed access. 

I know this is related to CORS, but like it expects CORS enabled on Facebook's side?

From what I understand: after loggin to Facebook, it redirects me back to my WebApi method registering ExternalLogin, and than back to my AngularApp. Is that correct?

Here's code of my login function:

function facebookLogin() {
    getExternalLogins().then(function (data) {
        var providerData = null;
        for (var i = 0; i < data.length; i++){
            if(data[i].Name == 'Facebook'){
                providerData = data[i];
                break;
            }
        }

        if(providerData != null) {
             window.location.href = serverBaseUrl + providerData.Url;
        }

    },
    function (error, status) {

    });
}

Update:

I've managed to redirect to Facebook's login page, thanks to CBroe's comment. The next problem is that after logging in, Facebook redirects me to my WebApi. How can I redirect user back to Angular app? WebApi can be called from various places, not only from example.com but from example1.com or example2.com also.

Maybe it would be a better idea to perform this login client-side using Facebook API, and then notify the server about it? But how to perform login on WebApi using FB authResponse?


回答1:


Try the following steps, they solved the issue for me (for a different login provider):

  1. Remove the built-in login page and controller, and the option to use ASP.Net identity from the web application; see this article.
  2. Add credentials in the $.ajax call (see below) of in $http:

 xhrFields: {
              withCredentials: true
            },
  1. Add to your web.config the following to enable CORS:

<add name="Access-Control-Allow-Origin" value="FACEBOOK_APP_URL" />
<add name="Access-Control-Allow-Credentials" value="true"/>


来源:https://stackoverflow.com/questions/22846510/handling-server-redirect-to-facebook-login-page-in-angularjs

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