这是Gmail API的"Java Quickstart"教程中给出的代码。以下是为应用程序创建凭据所需的操作:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.build();
System.out.println("Please open the following URL in your browser then type"
+ " the authorization code:\n" + url);
// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = null;
try {
code = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// Generate Credential using retrieved code.
GoogleTokenResponse response = null;
try {
response = flow.newTokenRequest(code)
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
} catch (IOException e) {
e.printStackTrace();
}
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(response);是否可以像这里一样自动执行上述过程,以获取凭据以供进一步使用?
下面的示例是针对Google任务的。
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS));发布于 2015-04-15 14:25:08
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(service_account)
.setServiceAccountScopes(
Collections.singleton("https://mail.google.com/"))
// .setServiceAccountPrivateKeyFromP12File(new
// File(certLocation))
.setServiceAccountPrivateKey(serviceAccountPrivateKey)
.setServiceAccountUser(senderid).build();发布于 2016-06-09 18:51:00
将此应用程序的用户凭据存储在目录中。
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".store/mail_credentials");为FileDataStoreFactory创建一个全局实例。
private static FileDataStoreFactory DATA_STORE_FACTORY;在获取凭据之前实例化DATA_STORE_FACTORY,最好是在静态块中。
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);从谷歌开发人员控制台下载并存储client_secrets.json。使用以下方法获取凭据:
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in
= GmailQuickStart.class.getResourceAsStream("/client_secrets.json");
GoogleClientSecrets clientSecrets
= GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow
= new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}每当调用上述方法时,它都会在提供给DATA_STORE_DIR的路径中查找StoredCredential。如果找到它,则代码按原样执行。如果没有,将打开一个浏览器,要求您登录并授权您的应用程序。这样生成的凭据将存储在DATA_STORE_DIR位置。只要StoredCredential存在,您的应用程序就不会请求许可。
https://stackoverflow.com/questions/29624292
复制相似问题