OAuth的与.NET返回HTTP 400谷歌数据API:坏请求 [英] OAuth with Google data API for .NET returning HTTP 400: Bad Request
问题描述
我想获得的OAuth与谷歌数据API的.NET库工作。不幸的是,每当我打电话GetUnauthorizedRequestToken,我得到一个400错误响应错误。这是我的code ...
OAuthParameters参数=新OAuthParameters(){
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
范围=https://docs.google.com/feeds/
回调= Request.RawUrl,
=是SignatureMethodHMAC-SHA1
};
OAuthUtil.GetUnauthorizedRequestToken(参数);
据我知道我正确地按照指示在这里: HTTP://$c$c.google.com/apis /gdata/docs/auth/oauth.html
任何帮助,这个问题将是非常美联社preciated!
编辑:2011年9月10日下午11时56 PST
首先,非常感谢你的意见!
所以我拨弄了一下周围,并获得未经授权的请求令牌的工作,但OAuth是还没有真正的工作...这里是一个更完整的code转储: - \
字符串标记=请求[oauth_token];
如果(!String.IsNullOrEmpty(令牌)){
OAuthParameters tParams =新OAuthParameters(){
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
范围= S_SCOPE,
回调= S_CALLBACK,
=是SignatureMethodHMAC-SHA1
};
tParams.Verifier =请求[oauth_verifier];
tParams.Token =令牌;
尝试 {
// HTTP://$c$c.google.com/apis/gdata/docs/auth/oauth.html
从回调URL // 1.提取令牌
//OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query,参数);
// 2.升级到一个访问令牌
OAuthUtil.GetAccessToken(tParams);
字符串accessToken = tParams.Token;
字符串accessTokenSecret = tParams.TokenSecret;
会话[SP] = tParams; //不用担心,我们甚至没有拿到这里还没有
返回RedirectToAction(目录);
}
赶上(System.Net.WebException前){
//打印出吨的东西(除去理智)
}
// ...,再从头开始
}
尝试 {
OAuthParameters参数=新OAuthParameters(){
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
范围= S_SCOPE,
回调= S_CALLBACK,
=是SignatureMethodHMAC-SHA1
};
OAuthUtil.GetUnauthorizedRequestToken(参数);
字符串approvalPageUrl = OAuthUtil.CreateUserAuthorizationUrl(参数);
ViewBag.AuthUrl = approvalPageUrl;
}
赶上(System.Net.WebException前){
//打印出更多的东西
}
这是我看到的错误(略作修改,以删除敏感数据,但是我将所有的符号,是以防有人认为这是一个编码错误):
X-的Content-Type-选项= nosniff
的X XSS-保护= 1;模式=块
内容长度= 386
缓存控制=私人,最大年龄= 0
内容类型= text / plain的;字符集= UTF-8
日期=日,2011 9月11日6时53分26秒格林尼治标准时间
过期=孙,2011 6时53分26秒格林尼治标准时间9月11日
服务器= GSE
/帐号/ OAuthGetAccessToken
signature_invalid
base_string:GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Dmydomain.com%26oauth_nonce%3D4432dc4bd59b4ea0b133ea52cb450062%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1315724016%26oauth_token%3D4%252FGeEWOLvQL_eGlj8zAdrzi7YPhmhS%26oauth_verifier%3DMkGYPy8qeZPRg7gLKKXsYIiM%26oauth_version%3D1.0
回调= http://mydomain.com/auth
ConsumerKey = mydomain.com
ConsumerSecret = RxGavGhuXi92sy3F,Q3DKcY_
随机数= 4430dc4bd59b4ea3b133ea52cb450062
范围= https://docs.google.com/feeds
=是SignatureMethod HMAC-SHA1
时间戳= 1315724016
令牌= 4 / GeAWOLvQL_eGlj1zEerzi7YPhmhS
TokenSecret =
验证= MkXLPy8qeZARq7aLKXKsYIiM
我通过这个挣扎,并能够把我的自己的MVC2类来处理整个过程。看一看,让我知道,如果这可以帮助你。
公共类GoogleController:ApplicationController中
{
//
// GET:/谷歌/
公众的ActionResult指数()
{
返回查看();
}
公众的ActionResult授权()
{
OAuthParameters参数= BuildParameters();
//生成令牌未经授权的请求,并生成URL
GetUnauthorizedRequestToken(参数);
字符串authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(参数);
//临时存储的参数和重定向到谷歌的授权
SaveParametersTokens(参数);
的Response.Redirect(authorizationUrl);
返回查看();
}
公众的ActionResult的Oauth()
{
//检索和更新的令牌临时认证
OAuthParameters参数= BuildParameters();
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query,参数);
//最后,得到我们所需要B @#$令牌!
OAuthUtil.GetAccessToken(参数);
//保存这些令牌到数据库
SaveParametersTokens(参数);
//世界上所有的成功,返回
返回RedirectToAction(指数,管理);
}
公众的ActionResult DeleteParametersTokens()
{
VAR oldTokens =(从吨context.GO_GoogleAuthorizeTokens选择T);
//如果有一个道理,叫谷歌将其删除
/ *如果(oldTokens.Count()大于0)
{
GO_GoogleAuthorizeToken令牌= oldTokens.First();
AuthSubUtil.revokeToken(tokens.Token,NULL);
} * /
//从数据库中删除的标记
context.GO_GoogleAuthorizeTokens.DeleteAllOnSubmit(oldTokens);
context.SubmitChanges();
//重定向到管理员的主页时的标记将被删除
返回RedirectToAction(指数,管理);
}
#地区的私人助手方法
私人无效GetUnauthorizedRequestToken(OAuthParameters参数)
{
字符串requestTokenUrl =https://www.google.com/accounts/OAuthGetRequestToken;
乌里requestUri =新的URI(的String.Format({0}范围= {1}?,requestTokenUrl,OAuthBase.EncodingPerRFC3986(parameters.Scope)));
//回调获取请求令牌时,才需要
布尔callbackExists = FALSE;
如果(!string.IsNullOrEmpty(parameters.Callback))
{
parameters.BaseProperties.Add(OAuthBase.OAuthCallbackKey,parameters.Callback);
callbackExists = TRUE;
}
字符串标题= OAuthUtil.GenerateHeader(requestUri,GET,参数);
System.Net.WebRequest请求= System.Net.WebRequest.Create(requestUri);
request.Headers.Add(头);
System.Net.WebResponse响应= request.GetResponse();
字符串结果=;
如果(响应!= NULL)
{
的System.IO.Stream responseStream = response.GetResponseStream();
就是System.IO.StreamReader读卡器=新就是System.IO.StreamReader(responseStream);
结果= reader.ReadToEnd();
}
如果(callbackExists)
{
parameters.BaseProperties.Remove(OAuthBase.OAuthCallbackKey);
}
//拆分结果,并更新参数
SortedDictionary<字符串,字符串> responseValues = OAuthBase.GetQueryParameters(结果);
parameters.Token = responseValues [OAuthBase.OAuthTokenKey]
parameters.TokenSecret = responseValues [OAuthBase.OAuthTokenSecretKey]
}
私人布尔SaveParametersTokens(OAuthParameters参数)
{
尝试
{
//先删除任何旧的
VAR oldTokens =(从吨context.GO_GoogleAuthorizeTokens选择T);
context.GO_GoogleAuthorizeTokens.DeleteAllOnSubmit(oldTokens);
context.SubmitChanges();
现在//创建一个新的
GO_GoogleAuthorizeToken newToken =新GO_GoogleAuthorizeToken
{
令牌= parameters.Token,
TokenSecret = parameters.TokenSecret
};
context.GO_GoogleAuthorizeTokens.InsertOnSubmit(newToken);
context.SubmitChanges();
}
赶上{返回false; }
返回true;
}
私人OAuthParameters BuildParameters()
{
//筑基参数
字符串范围=https://www.google.com/calendar/feeds/ https://docs.google.com/feeds/ https://mail.google.com/mail/feed/atom/;
字符串回调=的String.Format(HTTP:// {0} /谷歌/的Oauth,Request.Url.Authority);
OAuthParameters参数=新OAuthParameters
{
ConsumerKey = kConsumerKey,
ConsumerSecret = kConsumerSecret,
范围=范围,
回调=回拨,
=是SignatureMethodHMAC-SHA1
};
//检查,看看是否我们已经保存令牌
VAR令牌=(从在context.GO_GoogleAuthorizeTokens选择);
如果(tokens.Count()大于0)
{
GO_GoogleAuthorizeToken令牌= tokens.First();
parameters.Token = token.Token;
parameters.TokenSecret = token.TokenSecret;
}
返回参数;
}
#endregion
}
I am trying to get OAuth working with the .NET library for Google Data API. Unfortunately, whenever I call GetUnauthorizedRequestToken, I get a 400 Bad Response error. Here is my code...
OAuthParameters parameters = new OAuthParameters() {
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
Scope = "https://docs.google.com/feeds/",
Callback = Request.RawUrl,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
As far as I know I am correctly following the instructions here: http://code.google.com/apis/gdata/docs/auth/oauth.html
Any help with this problem would be much appreciated!
EDIT: 9/10/2011 11:56 PM PST
First of all, thank you so much for the comments!
So I've fiddled around a bit and got the Unauthorized Request Token working, but OAuth is still not really working... here is a more complete code dump :-\
string token = Request["oauth_token"];
if (!String.IsNullOrEmpty(token)) {
OAuthParameters tParams = new OAuthParameters() {
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
Scope = S_SCOPE,
Callback = S_CALLBACK,
SignatureMethod = "HMAC-SHA1"
};
tParams.Verifier = Request["oauth_verifier"];
tParams.Token = token;
try {
// http://code.google.com/apis/gdata/docs/auth/oauth.html
// 1. Extract token from the callback URL
//OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
// 2. Upgrade to an access token
OAuthUtil.GetAccessToken(tParams);
string accessToken = tParams.Token;
string accessTokenSecret = tParams.TokenSecret;
Session["sp"] = tParams; // don't worry, we don't even get here yet
return RedirectToAction("List");
}
catch (System.Net.WebException ex) {
// print out tons of stuff (removed for sanity)
}
//... and start over again
}
try {
OAuthParameters parameters = new OAuthParameters() {
ConsumerKey = DOMAIN_NAME,
ConsumerSecret = SECRET_KEY,
Scope = S_SCOPE,
Callback = S_CALLBACK,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string approvalPageUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
ViewBag.AuthUrl = approvalPageUrl;
}
catch (System.Net.WebException ex) {
// print out more stuff
}
and this is the error I am seeing (slightly modified to remove sensitive data, however I left all the symbols as-is in case someone thinks this is an encoding error):
X-Content-Type-Options = nosniff
X-XSS-Protection = 1; mode=block
Content-Length = 386
Cache-Control = private, max-age=0
Content-Type = text/plain; charset=UTF-8
Date = Sun, 11 Sep 2011 06:53:26 GMT
Expires = Sun, 11 Sep 2011 06:53:26 GMT
Server = GSE
/accounts/OAuthGetAccessToken
signature_invalid
base_string:GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Dmydomain.com%26oauth_nonce%3D4432dc4bd59b4ea0b133ea52cb450062%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1315724016%26oauth_token%3D4%252FGeEWOLvQL_eGlj8zAdrzi7YPhmhS%26oauth_verifier%3DMkGYPy8qeZPRg7gLKKXsYIiM%26oauth_version%3D1.0
Callback = http://mydomain.com/auth
ConsumerKey = mydomain.com
ConsumerSecret = RxGavGhuXi92sy3F-Q3DKcY_
Nonce = 4430dc4bd59b4ea3b133ea52cb450062
Scope = https://docs.google.com/feeds
SignatureMethod = HMAC-SHA1
Timestamp = 1315724016
Token = 4/GeAWOLvQL_eGlj1zEerzi7YPhmhS
TokenSecret =
Verifier = MkXLPy8qeZARq7aLKXKsYIiM
I struggled through this and was able to put together my own MVC2 class to handle this whole process. Take a look and let me know if this helps you out.
public class GoogleController : ApplicationController
{
//
// GET: /Google/
public ActionResult Index()
{
return View();
}
public ActionResult Authorize()
{
OAuthParameters parameters = BuildParameters();
// build the token for unauthorized requests and generate the url
GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
// store the parameters temporarily and redirect to google for authorization
SaveParametersTokens(parameters);
Response.Redirect(authorizationUrl);
return View();
}
public ActionResult Oauth()
{
// retrieve and update the tokens for temporary authentication
OAuthParameters parameters = BuildParameters();
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
// finally, get the token we need b@#$!!!
OAuthUtil.GetAccessToken(parameters);
// save those tokens into the database
SaveParametersTokens(parameters);
// all the success in the world, return back
return RedirectToAction("Index", "Admin");
}
public ActionResult DeleteParametersTokens()
{
var oldTokens = (from t in context.GO_GoogleAuthorizeTokens select t);
// if there is a token, call google to remove it
/*if (oldTokens.Count() > 0)
{
GO_GoogleAuthorizeToken tokens = oldTokens.First();
AuthSubUtil.revokeToken(tokens.Token, null);
}*/
// delete the tokens from the database
context.GO_GoogleAuthorizeTokens.DeleteAllOnSubmit(oldTokens);
context.SubmitChanges();
// redirect to the administrator homepage when the tokens are deleted
return RedirectToAction("Index", "Admin");
}
#region private helper methods
private void GetUnauthorizedRequestToken(OAuthParameters parameters)
{
String requestTokenUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
Uri requestUri = new Uri(string.Format("{0}?scope={1}", requestTokenUrl, OAuthBase.EncodingPerRFC3986(parameters.Scope)));
// callback is only needed when getting the request token
bool callbackExists = false;
if (!string.IsNullOrEmpty(parameters.Callback))
{
parameters.BaseProperties.Add(OAuthBase.OAuthCallbackKey, parameters.Callback);
callbackExists = true;
}
string headers = OAuthUtil.GenerateHeader(requestUri, "GET", parameters);
System.Net.WebRequest request = System.Net.WebRequest.Create(requestUri);
request.Headers.Add(headers);
System.Net.WebResponse response = request.GetResponse();
string result = "";
if (response != null)
{
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream);
result = reader.ReadToEnd();
}
if (callbackExists)
{
parameters.BaseProperties.Remove(OAuthBase.OAuthCallbackKey);
}
// split results and update parameters
SortedDictionary<string, string> responseValues = OAuthBase.GetQueryParameters(result);
parameters.Token = responseValues[OAuthBase.OAuthTokenKey];
parameters.TokenSecret = responseValues[OAuthBase.OAuthTokenSecretKey];
}
private bool SaveParametersTokens(OAuthParameters parameters)
{
try
{
// first delete any old ones
var oldTokens = (from t in context.GO_GoogleAuthorizeTokens select t);
context.GO_GoogleAuthorizeTokens.DeleteAllOnSubmit(oldTokens);
context.SubmitChanges();
// now create a new one
GO_GoogleAuthorizeToken newToken = new GO_GoogleAuthorizeToken
{
Token = parameters.Token,
TokenSecret = parameters.TokenSecret
};
context.GO_GoogleAuthorizeTokens.InsertOnSubmit(newToken);
context.SubmitChanges();
}
catch { return false; }
return true;
}
private OAuthParameters BuildParameters()
{
// build the base parameters
string scope = "https://www.google.com/calendar/feeds/ https://docs.google.com/feeds/ https://mail.google.com/mail/feed/atom/";
string callback = String.Format("http://{0}/Google/Oauth", Request.Url.Authority);
OAuthParameters parameters = new OAuthParameters
{
ConsumerKey = kConsumerKey,
ConsumerSecret = kConsumerSecret,
Scope = scope,
Callback = callback,
SignatureMethod = "HMAC-SHA1"
};
// check to see if we have saved tokens
var tokens = (from a in context.GO_GoogleAuthorizeTokens select a);
if (tokens.Count() > 0)
{
GO_GoogleAuthorizeToken token = tokens.First();
parameters.Token = token.Token;
parameters.TokenSecret = token.TokenSecret;
}
return parameters;
}
#endregion
}
这篇关于OAuth的与.NET返回HTTP 400谷歌数据API:坏请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!