英文:
How to set credential for Google service account using JSON key added into application.yml in spring boot?
问题
google-drive:
type: "service_account"
project_id: "xx-387809"
private_key_id: "xxxxxxx"
private_key: "-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n"
client_email: "xxxxx-387809.iam.gserviceaccount.com"
client_id: "00000000"
auth_uri: "https://accounts.google.com/o/oauth2/auth"
token_uri: "https://oauth2.googleapis.com/token"
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs"
client_x509_cert_url: "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx-387809.iam.gserviceaccount.com"
universe_domain: "googleapis.com"
英文:
I am doing in google api service using google service account. I have this problem how to set value for builder to credential this api. How to set it in JSON key
public GoogleCredential googleCredential() throws GeneralSecurityException, IOException {
Collection<String> scope = new ArrayList<String>();
scope.add("https://www.googleapis.com/auth/drive");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Builder credentialBuilder = new Builder(httpTransport, jsonFactory);
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("xxx")
.setServiceAccountScopes(scope)
)
.build();
}
I want to create application.yml to store this JSON key like this:
google-drive:
type: "service_account",
project_id: "xx-387809",
private_key_id: "xxxxxxx",
private_key: "-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n",
client_email: "xxxxx-387809.iam.gserviceaccount.com",
client_id: "00000000",
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_x509_cert_url: "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx-387809.iam.gserviceaccount.com",
universe_domain: "googleapis.com"
to run my service with this config
答案1
得分: 1
你可以将 JSON 密钥作为字符串应用属性传递,例如在 application.yml
文件中:
google:
privateKey:
json: ''{"type":"service_account","project_id":"mocked-project","private_key_id":"mocked_private_key","private_key":"-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n","client_email":"mocked-service-account@mocked-project.iam.gserviceaccount.com","client_id":"123577123897123","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/mock-service-account%40mocked-project.iam.gserviceaccount.com"}'
然后,你可以使用 fromStream()
方法从输入流中解析凭据,如下所示:
InputStream in = new ByteArrayInputStream(privateKeyJson.getBytes());
GoogleCredential cr = GoogleCredential.fromStream(in);
最后,在获取凭据后,你可以使用 GoogleCredentials.Builder()
来设置服务帐户属性。以下是一个示例:
GoogleCredential cr = GoogleCredential.fromStream(in);
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jacksonFactory)
.setServiceAccountId(cr.getServiceAccountId())
.setServiceAccountPrivateKey(cr.getServiceAccountPrivateKey())
.setServiceAccountPrivateKeyId(cr.getServiceAccountPrivateKeyId())
.setTokenServerEncodedUrl(cr.getTokenServerEncodedUrl())
.setServiceAccountId("xxx")
.setServiceAccountScopes(scope)
.build();
英文:
You can pass the JSON key as a String application property for example on the application.yml
google:
privateKey:
json: '{"type":"service_account","project_id":"mocked-project","private_key_id":"mocked_private_key","private_key":"-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n","client_email":"mocked-service-account@mocked-project.iam.gserviceaccount.com","client_id":"123577123897123","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/mock-service-account%40mocked-project.iam.gserviceaccount.com"}'
Then you can parse the credentials with the fromStream()
method GoogleCredentials
, for example:
InputStream in = new ByteArrayInputStream(privateKeyJson.getBytes());
GoogleCredential cr = GoogleCredential.fromStream(in);
Finally, after obtaining the credentials you can use the GoogleCredentials.Builder()
to set the service account properties
Here is an example:
GoogleCredential cr = GoogleCredential.fromStream(in);
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jacksonFactory)
.setServiceAccountId(cr.getServiceAccountId())
.setServiceAccountPrivateKey(cr.getServiceAccountPrivateKey())
.setServiceAccountPrivateKeyId(cr.getServiceAccountPrivateKeyId())
.setTokenServerEncodedUrl(cr.getTokenServerEncodedUrl())
.setServiceAccountId("xxx")
.setServiceAccountScopes(scope)
.build();
答案2
得分: 0
public class DriveWithServiceAccountQuickstart {
private static final String APPLICATION_NAME = "你厉害的应用";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/路径/到/你的/从谷歌API控制台下载的服务帐户密钥.json";
public static void main(String... args) throws IOException, GeneralSecurityException {
// 创建一个新的经授权的API客户端服务
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(SCOPES));
Drive driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
// 打印最多10个文件的名称和ID。
FileList result = driveService.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("未找到文件。");
} else {
System.out.println("文件:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
英文:
Try something like this.
public class DriveWithServiceAccountQuickstart {
private static final String APPLICATION_NAME = "your awesome app";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/path/to/your/service-account-key-downloaded-from-google-api-console.json";
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(SCOPES));
Drive driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
// Print the names and IDs for up to 10 files.
FileList result = driveService.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论