So, I'm trying to get the Service Application Credentials on my localhost and I'm encountering some problems. I created and downloaded the json key and I want to secure them instead of letting them in plain text.
I want to know the best way to do this. I have this code:
fun getServiceAccountCredentials(
pathToFallBackCredentialsFile: String
): ServiceAccountCredentials {
return try {
getApplicationDefault() as ServiceAccountCredentials
} catch (e: IOException) {
return ServiceAccountCredentials.fromStream(FileInputStream(pathToFallBackCredentialsFile))
} catch (e: ClassCastException) {
return ServiceAccountCredentials.fromStream(this::class.java.classLoader.getResourceAsStream(pathToFallBackCredentialsFile))
}
}
The problem here is that my JSON file is exposed in plain text in my repository.
Options
I found a solution.
I activated the Secret Manager from GCP and I've added the JSON file there.
To take the secret in a java/kotlin application(without spring, if you have spring you can use "spring-cloud-gcp-starter-secretmanager"), I used the following piece of code.
fun accessSecretVersion(secretId: String?, versionId: String?): String {
val googleCredentials = GoogleCredentials.getApplicationDefault() as UserCredentials
val projectId = googleCredentials.quotaProjectId
return getSecret(projectId, secretId, versionId)
}
fun getSecret(projectId: String?, secretId: String?, versionId: String?): String {
SecretManagerServiceClient.create().use { client ->
val secretVersionName = SecretVersionName.of(projectId, secretId, versionId)
val response = client.accessSecretVersion(secretVersionName)
return response.payload.data.toStringUtf8()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.