Facebook登录在本地主机上可以工作,但在网络主机上却不行。

3
我有一个如下所示的类:

public class FacebookScopedClient : IAuthenticationClient
{
    private string appId;
    private string appSecret;
    private string scope;

    private const string baseUrl = "https://www.facebook.com/dialog/oauth?client_id=";
    public const string graphApiToken = "https://graph.facebook.com/oauth/access_token?";
    public const string graphApiMe = "https://graph.facebook.com/me?";

    private  string GetHTML(string URL)
    {
        string connectionString = URL;

        try
        {
            var myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
            myRequest.Credentials = CredentialCache.DefaultCredentials;
            //// Get the response
            WebResponse webResponse = myRequest.GetResponse();
            Stream respStream = webResponse.GetResponseStream();
            ////
            var ioStream = new StreamReader(respStream);
            string pageContent = ioStream.ReadToEnd();
            //// Close streams
            ioStream.Close();
            respStream.Close();
            return pageContent;
        }
        catch (Exception)
        {
        }
        return null;
    }

    private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
    {
        string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);
        if (string.IsNullOrEmpty(token))
        {
            return null;
        }
        string access_token = token.Substring(token.IndexOf("access_token=", StringComparison.Ordinal), token.IndexOf("&", System.StringComparison.Ordinal));
        token = access_token.Replace("access_token=", string.Empty);
        string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);

        // this dictionary must contains
        var userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
        userData.Add("access_token", token);
        return userData;
    }

    public FacebookScopedClient(string appId, string appSecret, string scope)
    {
        this.appId = appId;
        this.appSecret = appSecret;
        this.scope = scope;
    }

    public string ProviderName
    {
        get { return "facebook"; }
    }

    public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
    {
        string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + scope;
        context.Response.Redirect(url);
    }

    public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
    {
        string code = context.Request.QueryString["code"];

        string rawUrl = context.Request.Url.OriginalString;
        //From this we need to remove code portion
        rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

        IDictionary<string, string> userData = GetUserData(code, rawUrl);

        if (userData == null)
            return new AuthenticationResult(false, ProviderName, null, null, null);

        string id = userData["id"];
        string username = userData["username"];
        userData.Remove("id");
        userData.Remove("username");

        var result = new AuthenticationResult(true, ProviderName, id, username, userData);
        return result;
    }
}

上述类在AuthConfig.cs中注册,如下所示。
OAuthWebSecurity.RegisterClient(
    new FacebookScopedClient("blablabla", "blablabla", 
        "read_stream,status_update,publish_actions,offline_access,user_friends"), "Facebook", facebooksocialData);

我可以在身份验证期间像这样使用它

[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
    AuthenticationResult result =
        OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));


    if (!result.IsSuccessful)
    {
        return RedirectToAction("ExternalLoginFailure");
    }
    if (result.ExtraData.Keys.Contains("access_token"))
    {
        Session["token"] = result.ExtraData["access_token"];


    }


    if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
    {
        return RedirectToLocal(returnUrl);
    }

    if (User.Identity.IsAuthenticated)
    {
        // If the current user is logged in add the new account
        OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
        return RedirectToLocal(returnUrl);
    }
    // User is new, ask for their desired membership name
    string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
    ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
    ViewBag.ReturnUrl = returnUrl;
    var client = new ComputerBeacon.Facebook.Graph.User("me", Session["token"].ToString());
    var firstName = client.FirstName;
    var lastName = client.LastName;
    var userName = client.Email;
    return View("ExternalLoginConfirmation",
                new RegisterExternalLoginModel
                    {
                        UserName = result.UserName,
                        FirstName = firstName,
                        LastName = lastName,
                        ExternalLoginData = loginData
                    });
}

现在这在本地工作正常,但当我上传到远程服务器时,由于某些奇怪的原因它不起作用。

AuthenticationResult result =
        OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

“从来没有成功。请问我做错了什么。我已经在developers.facebook.com更新了必要的URL。”
“谢谢。”
2个回答

1

嗯,我看到了问题。

public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
    {
        string code = context.Request.QueryString["code"];

        string rawUrl = context.Request.Url.OriginalString;
        if (rawUrl.Contains(":80/"))
            {
            rawUrl = rawUrl.Replace(":80/", "/");
            }
        if (rawUrl.Contains(":443/"))
        {
            rawUrl = rawUrl.Replace(":443/", "/");
        }
        //From this we need to remove code portion
        rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

        IDictionary<string, string> userData = GetUserData(code, rawUrl);

        if (userData == null)
            return new AuthenticationResult(false, ProviderName, null, null, null);

        string id = userData["id"];
        string username = userData["username"];
        userData.Remove("id");
        userData.Remove("username");

        var result = new AuthenticationResult(true, ProviderName, id, username, userData);
        return result;
    }

感谢http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/提供的所有内容。
感谢大家的贡献。

这解决了问题,谢谢你发布解决方案。我整整折腾了一天... - Zia Ul Rehman Mughal
你能解释一下你做了什么吗? - Leandro Bardelli
链接已失效。 - Leandro Bardelli

0

Facebook使用您提供的URL来进行其开放式认证所必需的操作。我怀疑您已经为本地主机设置了该URL,因此Facebook不允许来自任何其他域的认证请求。

如果确实是这种情况,您需要设置另一个Facebook应用程序配置文件(称其为“AppName Production”或其他名称),并为该应用程序的站点URL设置Web主机的域名:

enter image description here

您可以在应用设置选项卡中找到此设置:

enter image description here


是的,我已经修改它以反映移动到远程服务器的情况。尽管我的是[code]http://someurl.com.ng,但我不能错过这个。 - Paul Plato

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接