使用 google 云翻译,只有一个令牌,没有密钥文件

Use google cloud translation with just a token and without keyfile

使用 google 云翻译时 API 我不想使用生成的密钥文件 (https://cloud.google.com/translate/docs/basic/setup-basic?hl=de#node.js)。我们使用部署到某个随机主机的 docker 个容器。出于明显的安全原因,我无法将密钥文件添加到我的源代码中以编译到 docker 容器中,并且我不想将密钥文件复制到部署了容器(或可能部署了!)的每个主机。

通常 APIs 可以使用我可以使用我的容器管理环境变量设置的令牌,然后当我必须扩展它或切换主机等时,我可以将它应用于容器的所有实例。 google 提供那种设置吗?我可以使用 REST 请求,不需要任何 sdk。

在我看来,唯一的选择是在我们的 gitlab 中添加密钥文件 json 作为环境变量,然后将文件构建到容器中。

或者是否有任何其他方式使用 google 翻译 API 仅使用令牌而不使用密钥文件?

Google 的 SDK 可以隐式使用默认服务帐户 (https://cloud.google.com/docs/authentication/production)。

编辑:这可能会解决您的问题:https://github.com/googleapis/google-api-go-client/issues/185

另外:https://godoc.org/golang.org/x/oauth2/google#CredentialsFromJSON

代码示例如下:

json := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON") // `{"type": "service_account", "project_id": "my-project", ...}`
ctx := context.Background()
jwtConfig, err := google.JWTConfigFromJSON([]byte(json), datastore.ScopeDatastore)
if err != nil {
    ...
}
ts := jwtConfig.TokenSource(ctx)
datastoreClient, err := datastore.NewClient(ctx, projectID, option.WithTokenSource(ts))

编辑2:

同时勾选 https://github.com/googleapis/google-auth-library-nodejs#loading-credentials-from-environment-variables

Loading credentials from environment variables
Instead of loading credentials from a key file, you can also provide them using an environment variable and the GoogleAuth.fromJSON() method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc).

Start by exporting your credentials:

$ export CREDS='{
  "type": "service_account",
  "project_id": "your-project-id",
  "private_key_id": "your-private-key-id",
  "private_key": "your-private-key",
  "client_email": "your-client-email",
  "client_id": "your-client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "your-cert-url"
}'
Now you can create a new client from the credentials:

const {auth} = require('google-auth-library');

// load the environment variable with our keys
const keysEnvVar = process.env['CREDS'];
if (!keysEnvVar) {
  throw new Error('The $CREDS environment variable was not found!');
}
const keys = JSON.parse(keysEnvVar);

async function main() {
  // load the JWT or UserRefreshClient from the keys
  const client = auth.fromJSON(keys);
  client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
  const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);