簡體   English   中英

帶有Google數據API的OAuth(.NET)返回HTTP 400:錯誤的請求

[英]OAuth with Google data API for .NET returning HTTP 400: Bad Request

我正在嘗試讓OAuth與.NET庫一起使用Google Data API。 不幸的是,每當我調用GetUnauthorizedRequestToken時,都會收到400錯誤的響應錯誤。 這是我的代碼...

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

據我所知,我正確地遵循了以下說明: http : //code.google.com/apis/gdata/docs/auth/oauth.html

任何有關此問題的幫助將不勝感激!

編輯:2011年9月10日晚上11:56

首先,非常感謝您的評論!

因此,我進行了一些擺弄,使“未經授權的請求令牌”正常工作,但是OAuth仍然無法正常工作...這是一個更完整的代碼轉儲:-\\

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
}

這就是我所看到的錯誤(稍作修改以刪除敏感數據,但是如果有人認為這是編碼錯誤,我將所有符號保持原樣):

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

我為此苦苦掙扎,並且能夠組合自己的MVC2類來處理整個過程。 看一看,讓我知道這是否對您有幫助。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM