2017-04-09 159 views
0

我使用谷歌https://developers.google.com/identity/sign-in/web/server-side-flow下面的例子到目前为止,我能够实现以下步骤:在客户端越来越TokenResponseException:401未经授权

  1. 用户认证(浏览器)
  2. 代码被返回和保存在服务器上db
  3. 请求验证码时TokenResponseException:401未经授权。

我检查以下内容:

  1. API启用
  2. https://developers.google.com/oauthplayground我测试了相同的客户端ID和客户端密钥接入和它的作品
  3. 阅读几乎每一个SO查询,这是与这个问题有关,但他们都没有真正帮助。
  4. 试图撤销所有用户权限并重新要求他们获取新代码。

下面是我使用的代码:

public void getUserAuthTokens(String authCode){ 
    try { 

     GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
       JacksonFactory.getDefaultInstance(),new FileReader(new ClassPathResource("static\\client_secret.json").getFile())); 

     List<String> scopes = new ArrayList<>(); 
     scopes.add("https://www.googleapis.com/auth/gmail.readonly"); 
     //String scopes[]={"https://www.googleapis.com/auth/gmail.readonly"}; 

     Collection<String> SCOPES 
       = Collections.unmodifiableCollection(
       Arrays.asList(
         new String[]{ 
           GmailScopes.GMAIL_READONLY 
         })); 
     GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),JacksonFactory.getDefaultInstance(), 
       "https://www.googleapis.com/oauth2/v4/token", 
       clientSecrets.getDetails().getClientId(), 
       clientSecrets.getDetails().getClientSecret(), 
       authCode).setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).setScopes(SCOPES).execute(); 


     String accessToken = tokenResponse.getAccessToken(); 
     System.out.print("Token is: "+accessToken); 
    }catch (IOException x){ 
     x.printStackTrace(); 

    } 

} 

一个侧面说明,如果我没有使用setRedirectUri(。clientSecrets.getDetails()getRedirectUris()获取(0)),然后,我就“重定向失配误差”

我将不胜感激对此有何想法,我从Standard Error Responses,谷歌的API返回,错误代码401未授权基于跑出

+0

伙计们我真的需要一些帮助在这里我无法破解这个 – user2145673

回答

0

经过大量的调试和搜索,我发现了一个可行的解决方案,我在这里发布这个帖子,以防有人遇到同样的问题。

这里是我使用的代码:

GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),JacksonFactory.getDefaultInstance(), 
       "https://www.googleapis.com/oauth2/v4/token", 
       clientSecrets.getDetails().getClientId(), 
       clientSecrets.getDetails().getClientSecret(), 
       authCode, "postmessage") 
       .execute(); 

你可以阅读更多的PostMessage的@Google+ Sign-in for server-side apps, exchanging auth code for access token

希望有所帮助。

0

指示与授权CRE问题为请求提供的dentials。您可能需要查看以下可能的原因:

  • OAuth访问令牌已过期,需要刷新。这可以通过尽早刷新访问令牌来避免,但代码也可以捕获此错误,刷新令牌并自动重试。
  • 提供了多个不匹配的授权;只选择一种模式。
  • OAuth访问令牌的绑定项目不匹配与提供的开发人员密钥关联的项目。
  • 授权标头为无法识别的格式或使用不受支持的凭证类型。

有关使用OAuth 2.0访问Google API的更多信息,请参阅此documentation。建议的解决方案在这个相关的SO post也可能有所帮助。

+0

嗯,我在代码发送到谷歌的阶段,以获得访问令牌,并在那里失败。你可以看到上面的相关代码。该错误被捕获块捕获,我可以看到堆栈跟踪中的错误。任何想法可能导致什么? – user2145673

相关问题