MVC4严重的OAuth问题

时间:2013-09-14 16:03:32

标签: c# asp.net-mvc facebook asp.net-mvc-4 oauth

我遇到了OAuth和Facebook的问题。我正在使用MVC4标准OAuth登录。我在本地没有这个问题,但在服务器上这证明是一个问题。

如果我将以下网址粘贴到浏览器中,则可以正常工作:

http://localhost:46260/Account/ExternalLoginCallback?ReturnUrl=%2FDashboard&__provider__=FacebookPro&__sid__=1234somesid456  // this is autogenerated

当我将Facebook中的应用程序的URL更改为当前域并粘贴此URL时,我会重新定向到不成功的登录页面:

http://freersvp.mytakeawaysite.com:80/Account/ExternalLoginCallback?ReturnUrl=%2FDashboard&__provider__=Facebook+Pro&__sid__=1234someid456  // note this is autogenerated

N.B 以上两个网址是重定向uri

以下网址是请求的内容并导致异常:

网址

https://graph.facebook.com/oauth/access_token?client_id=52*********37&redirect_uri=http%3a%2f%2ffreersvp.mytakeawaysite.com%3a80%2fAccount%2fExternalLoginCallback%3fReturnUrl%3d%252FDashboard%26__provider__%3dFacebook%2bPro%26__sid__%3d3c92eb7e84304afc931ef0ea7b62f56a&client_secret=2123***********4256&code=AQAQIJsj-ondldllVYKdpxJaZouqrlg9sjTcfUxyWhAw8MXbD2DvsOSujg2m7E3s3cvNusCI0ZZoJAuGgu_FLkPyjYMQAkTWDVyHTcAoJD-tezyXgn0vhoFzX3FmuRBHYpyJEM-dk0KgF5ugsTHo9yGjBjrcfMDUGu9IxkKQ36k3gMrwocM1_l5t342Q2kIOHdt8pPcyrs--NzgNyZv48vSq7jkZwuQ95xRjUHG5J-ptcgq0l2BlqjzHDDuvIFH23lpMWHzzqdejdj5ejukz7t_Fnhx-mrpVdcRYhP3JeZ2UOTjAyKQmUB3rInooECcjq4c

异常

  {
       "error": {
          "message": "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request",
          "type": "OAuthException",
          "code": 100
       }
    }

string token确实在以下代码的GetUserData函数中返回null:

我正在使用FacebookScopedClient:

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 static string GetHTML(string URL)
    {
        string connectionString = URL;

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

    private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
    {
        SessionControl ctl = new SessionControl();
        ctl.SaveParam("redirecturi", redirectURI, -3);
        ctl.Dispose();
        string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);

        if(token == null || token == "")
        {

            return null;
        }
        string access_token = token.Substring(token.IndexOf("access_token="), token.IndexOf("&"));
        string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);

        try
        {


        }
        catch { }
        // this dictionary must contains
        Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
        userData.Add("accesstoken", access_token);

        try
        {
            userData.Add("id", userData["id"]);
        }
        catch { }
        return userData;
    }

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

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

    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["email"];

        if(username == null || username == "")
        {
            username = userData["username"];
        }
        //userData.Remove("id");
        userData.Remove("username");

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

3 个答案:

答案 0 :(得分:3)

运行你的发布网址后,通过网址解码器导致错误,问题在于某些原因你的网址编码整个查询字符串而不仅仅是网址。

你会在那个网址中注意到一堆%26项,这些是网址编码的&amp;这就是抛出错误的原因。 Facebook解析器看到%26而不是&amp;并将其视为一个单一参数。

&amp;&amp;发送到页面时分隔url查询字符串参数。如果没有完整的代码,我无法告诉你在哪里查看,但在代码中的某些地方,您可以完整地编码整个查询字符串,并且需要找到该段代码并仅对嵌入的URL进行编码。

读完之后可以试试这个理论。

我认为你的代码是从Facebook接收这些东西,url编码,然后你的系统重新编码它。尝试接收任何收到的东西,然后首先对其进行解码,操纵它,然后根据需要重新编码。

希望这会有所帮助

答案 1 :(得分:0)

在Facebook应用程序中尝试使用沙盒模式。

答案 2 :(得分:-1)

注意到您的URL的查询字符串,我从Stackoverflow找到了答案。请查看它是否解决了您的问题: https://stackoverflow.com/a/16699058/2005136

史蒂夫S发布了回复:

“在我们的例子中,我们做了一些不寻常的事情(所以这可能与你的情况无关)。我们的redirect_uri是一个URL,其中一个URL作为编码路径元素嵌入.URL中的URL,双倍 - 传递给FB时编码,已经开始导致Facebook API服务器出现问题。

我们通过将嵌套URL的编码更改为长十六进制数而不是%编码来解决此问题,因此所有Facebook服务器都看到一个简单的redirect_uri,其中包含路径中的一些十六进制,不受正常URL编码/解码的影响。“< / p>