LInkedIn oAuth2请求令牌400错误请求

时间:2013-06-10 15:35:14

标签: c# asp.net-mvc linkedin

我正在与LinkedIN API争夺第二天,每次我尝试获取令牌时,我都会收到400 Bad Request。

这是我的代码,也许有人可以帮忙解决这个问题?

public void RequestAuthentication(System.Web.HttpContextBase context, System.Uri returnUrl)
{
    string url = String.Format("https://www.linkedin.com/uas/oauth2/authorization?response_type=code" +
                 "&client_id={0}" +
                 "&scope={1}" +
                 "&state={3}" +
                 "&redirect_uri={2}",this._consumerKey,_scope,HttpUtility.UrlEncode(returnUrl.ToString()),Guid.NewGuid().ToString());
    context.Response.Redirect(url);
}

public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
{
    //TODO: check CSRF
    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=[^&]*", "");

    string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
    string postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code,HttpUtility.UrlEncode(context.Request.QueryString["ReturnUrl"]), _consumerKey, _consumerSecret);

    //WebClient client = new WebClient();
    //var getReq =  client.DownloadString(authUrl + "?" + postData);

    HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + postData) as HttpWebRequest;
    webRequest.Method = "POST";

    //This "application/x-www-form-urlencoded"; line is important
    webRequest.ContentType = "application/x-www-form-urlencoded";

    webRequest.ContentLength = postData.Length;

    StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
    requestWriter.Write(postData);
    requestWriter.Close();

    StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
}

有什么想法?也许有人在过去解决了类似问题?

2 个答案:

答案 0 :(得分:0)

您必须在

中使用相同的 redirect_uri
public void RequestAuthentication(System.Web.HttpContextBase context, System.Uri returnUrl)

并且

public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)

功能。但是在你的代码 redirect_uri 的第一个函数 HttpUtility.UrlEncode(returnUrl.ToString())和第二个函数 HttpUtility.UrlEncode(context.Request.QueryString [“ReturnUrl “])不一样(我认为)。因此,请确保您已解决此问题。你可以使用代码。

答案 1 :(得分:0)

我刚调试了这个,这是我在成功之前尝试过的一些事情。我不确定哪一个是正确的,所以我会把它们全部放下,以防万一你需要从哪里开始:

  • HTTP协议1.1
  • 添加content-type: application/x-www-form-urlencoded标题
  • 不要刷新授权码返回页面的响应; URL参数中的代码(PHP中的$_GET['code'])显然无法重复使用(another answer表示它每20秒到期一次)
    • 换句话说,不要尝试重新使用或缓存授权码,尽快将其直接流入访问令牌请求
  • 尝试使用其他应用程序(如SoapUI或Fiddlr)命中端点以显示它正在工作,并更清楚地看到一些标头
    • 话虽如此,查看响应标题(不仅仅是响应代码)可能会有所帮助
  • 将数据作为POST内容发送,而不是作为URL参数

请注意,400错误表示格式错误的请求(400 BAD request HTTP error code meaning?)并非遗漏资源(404),如果您考虑得太快,这也可能是错误的。

相关问题