![](/img/trans.png)
[英]How do I create an Access Token from Service Account Credentials using REST API using JAVA?
[英]google api access token null for local java client with service account
我創建了一個服務帳戶來使用來自本地 Java 客戶端的 Google 聊天(不是機器人)。 我的目標是將 flowdock 數據遷移到 Google 聊天。
我嘗試了不同的方法來使用服務帳戶獲取訪問令牌,並查看了幾個文檔和論壇......
證書加載了所有證書信息。 但訪問令牌保持為空。
public class ChatScopes {
static final String CHAT_SPACES = "https://chat.googleapis.com/v1/spaces";
static final String CLOUD_AUTH = "https://www.googleapis.com/auth/cloud-platform";
static final String CHAT_MESSAGES = "https://www.googleapis.com/chat.messages.create";
static final String CHAT_SPACES_2 = "https://www.googleapis.com/chat.spaces.create";
static final List<String> scopes = Lists.newArrayList(
ChatScopes.CLOUD_AUTH,
ChatScopes.CHAT_SPACES,
ChatScopes.CHAT_SPACES_2,
ChatScopes.CHAT_MESSAGES);
}
...
GoogleCredentials credentials = GoogleCredentials
.fromStream(AuthenticationService.class.getResourceAsStream(CERT_FILE))
.createScoped(ChatScopes.scopes);
1.a
AccessToken token = credentials.refreshAccessToken(); // IOException: Error parsing token refresh response. Expected value access_token not found.
1.b
AccessToken token = credentials.getAccessToken(); // token is null
GoogleCredential credentials = GoogleCredential
.fromStream(AuthenticationService.class.getResourceAsStream(CERT_FILE_2))
.createScoped(Collections.singleton(ChatScopes.CHAT_SPACES));
return new HangoutsChat.Builder(httpTransport, JSON_FACTORY, credentials )
.setApplicationName(APP_NAME)
.build();
.build();
使用 hangoutsChat 請求時的響應,因為訪問令牌保持為空(無論是否調用刷新和/或 getAccessToken)
獲取 https://chat.googleapis.com/v1/spaces
{
"code": 401,
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING"
}
],
"errors": [
{
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Login Required.",
"reason": "required"
}
],
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
看來我們需要在這里編寫一些干凈的代碼。 該錯誤實際上來自錯誤的范圍聲明。 添加聊天機器人(為什么我不需要機器人?)讓我進步了。
范圍
public class ChatScopes {
static final String CLOUD_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat";
static final String CHAT_BOT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
static final List<String> scopes = Lists.newArrayList(
CLOUD_SCOPE,
CHAT_SCOPE,
CHAT_BOT_SCOPE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.