2012-02-17 82 views
4

我发现我可以通过OAuth 2.0,当我重定向URI是认证为“urn:IETF:WG:OAuth的:2.0:OOB”,但用户被迫复制代码,然后返回一个活动并将其粘贴到一个字段中。我希望体验比这更优雅。当重定向URI为“http:// localhost”的,(即使是返回的接入代码)我无法换取一个访问令牌API。这里是我的交易所代码:的Oauth 2不能为接入令牌交换代码,返回“invalid_grant”

  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
        0); 
      nameValuePairs.add(new BasicNameValuePair("client_id", 
        OAuth2ClientCredentialsMark1.CLIENT_ID)); 
      nameValuePairs.add(new BasicNameValuePair("client_secret", 
        OAuth2ClientCredentialsMark1.CLIENT_SECRET)); 
      nameValuePairs.add(new BasicNameValuePair("code", accessCode)); 
      nameValuePairs.add(new BasicNameValuePair("grant_type", 
        "authorization_code")); 
      nameValuePairs.add(new BasicNameValuePair("redirect_uri", 
        OAuth2ClientCredentialsMark1.REDIRECT_URI)); 
        //"http://localhost" 

      String url = "https://accounts.google.com/o/oauth2/token"; 
      //url += URLEncodedUtils.format(nameValuePairs, "utf-8"); 

      Log.d("print", url); 
      HttpPost hPost = new HttpPost(
        url); 
      hPost.setHeader("content-type", "application/x-www-form-urlencoded"); 

      hPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

该代码总是返回{ “错误”: “invalid_grant”}是什么给了?

我的应用程序是基于样本@https://github.com/ddewaele/LatitudeOAuth2Sample的,我一直在关注本教程@http://code.google.com/apis/accounts/docs/OAuth2InstalledApp.html

+0

我有同样的问题。使用Scala而不是Java,但除此之外它是相同的。我使用http:// localhost:9000作为重定向URI。 – Magnus 2012-03-07 16:23:15

+0

我在安装的应用程序上面临OAuth的相同问题。你有没有解决这个问题?请给出意见。 – Khushboo 2013-02-05 11:28:24

回答

3

看来,你的代码是正确的。错误来自OAuth2 spec section-5.2

所提供的授权许可(例如授权码,资源所有者证书)或刷新令牌无效,已过期,撤销,不匹配URI的授权请求中使用,或发出给另一客户端的重定向。

很可能,您的应用程序尚未得到用户的授权。


为了回答您的问题有关:

用户被强制复制代码,然后返回一个活动,并将其粘贴到现场

你能澄清什么样的oauth2 flow (scenario),你在发展吗?

0
{ 
    "access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc", 
    "token_type" : "Bearer", 
    "expires_in" : 3600, 
    "refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74" 
} 

当您第一次尝试为您的应用程序获取access_token时,您会获得以上信息。并且在访问令牌过期一小时后,您可以使用refresh_token获取新的access_token ....这里是您的链接https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Refreshing_a_Token

1

如以下线程所示,它可能是TIMING错误。确保你的服务器是与世界时钟同步可能只是防止invalid_grant错误完全。

我对我的只有一台服务器那样的问题,而事实上,它是唯一一个40秒的出场世界时钟(这是在未来)。我以前ntpdate强行更改日期,并安装了ntp服务。这是一个Linux机器。

https://groups.google.com/forum/?fromgroups=#!topic/google-analytics-data-export-api/4uNaJtquxCs

相关问题