通过.NET HttpWebRequest检索OAuth验证码

时间:2013-08-05 15:18:43

标签: quickbooks intuit-partner-platform

我正在尝试使用HttpWebRequest / HttpWebResponse复制通常通过“Connect to QuickBooks”按钮完成的OAuth步骤。

首先抓取请求令牌并生成授权链接很容易:

private const string oauthBaseUrl = "https://oauth.intuit.com/oauth/v1";
private const string urlRequestToken = "/get_request_token";
private const string urlAccessToken = "/get_access_token";
private const string verifyUrl = "https://appcenter.intuit.com";
private const string authorizeUrl = "https://appcenter.intuit.com/Connect/Begin";

...

var consumerContext = new OAuthConsumerContext
                        {
                            ConsumerKey = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(ckSS),
                            ConsumerSecret = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(csSS),
                            SignatureMethod = SignatureMethod.HmacSha1
                        };
IOAuthSession session = new OAuthSession(consumerContext, oauthBaseUrl + urlRequestToken, authorizeUrl, oauthBaseUrl + urlAccessToken);
IToken requestToken = session.GetRequestToken();
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);

然后,当我在授权链接上请求网站时,我会抓住在set-cookie字符串中生成的请求验证码:

var requestAuth = (HttpWebRequest) WebRequest.Create(authorizationLink);
requestAuth.Method = "GET";
requestAuth.ContentType = "application/x-www-form-urlencoded";
requestAuth.Accept = "text/html, application/xhtml+xml, */*";
requestAuth.Headers.Add("Accept-Encoding", "gzip, deflate");
requestAuth.Headers.Add("Accept-Language", "en-us");
requestAuth.Host = "appcenter.intuit.com";
requestAuth.KeepAlive = true;
var responseAuth = (HttpWebResponse) requestAuth.GetResponse();
Stream answerAuth = responseAuth.GetResponseStream();
var _answerAuth = new StreamReader(answerAuth);
string htmlAuth = _answerAuth.ReadToEnd();

// Need to grab the request verification code embedded in the set-cookie string
string cookies = responseAuth.Headers.Get("Set-Cookie");
int idx = cookies.IndexOf("__RequestVerificationToken", StringComparison.Ordinal);
if (idx > 0)
{
    int startIndex = cookies.IndexOf("=", idx, StringComparison.InvariantCultureIgnoreCase);
    int endIndex = cookies.IndexOf(";", startIndex + 1, StringComparison.InvariantCultureIgnoreCase);

    requestVerificationCode = cookies.Substring(startIndex + 1, endIndex - (startIndex + 1));
    postDataString += requestVerificationCode;
}

据我了解,需要使用请求验证码才能获得附加到回调网址的postdata中返回的OAuth验证码,而后者又需要获取访问令牌。

这就是困难的开始。使用Fiddler2,我发现生成OAuth验证码的登录URL为https://appcenter.intuit.com/Account/LogOnJson。但无论我尝试使用HttpWebRequest复制HTTP POST多少,我得到的回报都是500错误。我想知道是否有人有这个步骤的实际例子?这甚至可能吗?我希望如此,因为拉动IE并像宏一样走完相同的步骤的选择太难看了。

对此有何帮助?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以下载dotnet示例应用以了解OAUTH流程的工作原理:

https://github.com/IntuitDeveloperRelations/IPP_Sample_Code

在web.config中设置您的应用密钥。