服务帐户(Service Account)是Google Cloud中一种特殊的账户类型,用于代表非人类用户(如应用程序或虚拟机)进行身份验证和授权。与个人用户账户不同,服务帐户专为服务器间通信设计。
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class GoogleApiAuthExample {
private static final String CREDENTIALS_FILE_PATH = "/path/to/your/service-account-key.json";
public static void main(String[] args) throws IOException, GeneralSecurityException {
// 1. 构建GoogleCredentials对象
GoogleCredentials credentials = GoogleCredentials.fromStream(
new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(Collections.singleton(DriveScopes.DRIVE));
// 2. 创建HTTP传输和JSON工厂
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
GsonFactory jsonFactory = GsonFactory.getDefaultInstance();
// 3. 构建API客户端
Drive service = new Drive.Builder(HTTP_TRANSPORT, jsonFactory,
new HttpCredentialsAdapter(credentials))
.setApplicationName("Google Drive API Java Quickstart")
.build();
// 现在可以使用service对象调用Google Drive API
System.out.println("认证成功,API客户端已创建");
}
}
错误现象:403 Forbidden
或Insufficient Permission
错误
原因:
解决方案:
错误现象:FileNotFoundException
解决方案:
错误现象:需要访问G Suite域数据时权限不足
解决方案:
createDelegated()
方法创建带委派的凭据GoogleCredentials credentials = GoogleCredentials.fromStream(
new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(Collections.singleton(DriveScopes.DRIVE))
.createDelegated("admin@yourdomain.com");
没有搜到相关的文章