Facebook的登录工作在本地主机,但不是在虚拟主机提供商 [英] Facebook Login works in localhost but not in webhost

查看:125
本文介绍了Facebook的登录工作在本地主机,但不是在虚拟主机提供商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

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像这样

The above class is registered in AuthConfig.cs Like so

OAuthWebSecurity.RegisterClient(
    new FacebookScopedClient("blablabla", "blablabla", 
        "read_stream,status_update,publish_actions,offline_access,user_friends"), "Facebook", facebooksocialData);

和我可以用这个鉴别过程中,像这样

And I get to use this During authentication like so

[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
                    });
}

现在这个工程100%,与预期的本地主机,但是当我上传到远程服务器,它不会为一些奇怪的原因工作。

Now this works 100% as expected in Localhost, but when I upload to a remote server, it does not work for some strange reason.

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

从未成功。请什么我做错了。我已经更新了neccessary URL的@ developers.facebook.com

is never successful. Please what am I doing wrong. I have updated the neccessary URL's @ developers.facebook.com

感谢

推荐答案

好,我看到了这个问题。

well I saw the problem.

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

由于<一个href=\"http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/\" rel=\"nofollow\">http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/其中,所有这些都来自反正

Thanks to http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/ which where all these came from anyway

谢谢大家的贡献。

这篇关于Facebook的登录工作在本地主机,但不是在虚拟主机提供商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆