Ishika Jain
Ishika Jain

Reputation: 1177

How to use the Service Account credentials for SecretManagerServiceClient without using a json file

I am using the below code for accessing the service account credentials, Not sure Since the secret manager does not accept a credential in their Create(), So I tried the second approach as per https://cloud.google.com/docs/authentication/production#passing_code. What Am I doing wrong?

        var text = File.ReadAllText(@"cred.json");
        JObject credential = JObject.Parse(text);

        SecretManagerServiceClientBuilder secretManagerServiceClientBuilder = new SecretManagerServiceClientBuilder()
        {
            JsonCredentials = o1,
        };
        SecretManagerServiceClient client = secretManagerServiceClientBuilder.Build();
        // Create the client.
        client = SecretManagerServiceClient.Create();

Upvotes: 2

Views: 2038

Answers (1)

Ishika Jain
Ishika Jain

Reputation: 1177

Found the solution -

Accessing the service account via code can be done in 2 ways -

  1. Check if the API accepts the credentials in the create method like for the storage bucket, then use the first approach.

        var credential = GoogleCredential.FromFile(jsonPath);
        var storage = StorageClient.Create(credential);
    
  2. If create() do not accept params then user the builder for that API Like SecretManagerServiceClientBuilder for the secret manager, KeyManagementServiceClientBuilder for KMS. Just replace the create part with the builder part.

    var text = File.ReadAllText(@"cred.json");
    SecretManagerServiceClientBuilder secretManagerServiceClientBuilder = new SecretManagerServiceClientBuilder()
    {
        JsonCredentials = text,
    };
    SecretManagerServiceClient client = secretManagerServiceClientBuilder.Build();
          SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);
    
        // Call the API.
        AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);
    
        // Convert the payload to a string. Payloads are bytes by default.
        String payload = result.Payload.Data.ToStringUtf8();
    

Upvotes: 2

Related Questions