【发布时间】:2021-04-12 11:49:27
【问题描述】:
我有一个自动邮件系统,它有一组已配置的 Gmail 帐户。 Google 强制用户使用 Oauth 进行邮件发送,因此我从 Google API Console 创建了一个新的客户端 ID 和客户端密钥。我已授权 Gmail 使用 a Python script 访问我的帐户,所以我已经有一个刷新令牌。
我的问题是我正在尝试使用带有刷新令牌的AuthorizationCodeFlow 获取新的访问令牌,但我得到了 null:
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.BasicAuthentication;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.util.store.MemoryDataStoreFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
public class Main {
public static void main(String[] args) throws IOException {
String clientId = "748679640358-....b.apps.googleusercontent.com";
String clientSecret = "tUI4ggLLexNc...MRM";
String refreshToken = "1//0...........ARAAGBESNwF-L9Ir988VdRV3oiTYOQwygPjmwKw5r9Bi82q7JuoF2CysWw6xzW3z3Tda18GU5A_JMgdkGKw";
List<String> scopes = Arrays.asList("https://mail.google.com/");
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
// Sends requests to the OAuth server
new NetHttpTransport(),
// Converts between JSON and Java
JacksonFactory.getDefaultInstance(),
// Your OAuth client ID
clientId,
// Your OAuth client secret
clientSecret,
// Tells the user what permissions they're giving you
scopes)
// Stores the user's credential in memory
.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
Credential credential;
try {
credential = flow.loadCredential(clientId);
} catch (IOException e) {
// Error getting login status
credential = null;
}
if (credential == null) {
TokenResponse tokenResponse = new TokenResponse().setRefreshToken(refreshToken);
credential = flow.createAndStoreCredential(tokenResponse, clientId);
}
String accessToken = credential.getAccessToken();
System.out.println(accessToken); // THIS PRINTS null
}
}
我不知道我错过了什么,任何形式的帮助都会非常感激
【问题讨论】:
标签: java oauth-2.0 google-oauth