Logan Theive

  • Home
  • Sitemap
Home  ›  Unable to Read Gcloud Auth Activate-service-account --key-file=[path]

Unable to Read Gcloud Auth Activate-service-account --key-file=[path]

Written By Amy Voinficand quinta-feira, 3 de março de 2022 Add Comment Edit

»Google Deject Auth Method

The gcp auth method allows Google Cloud Platform entities to authenticate to Vault. Vault treats Google Deject as a trusted third party and verifies authenticating entities against the Google Cloud APIs. This backend allows for authentication of:

  • Google Cloud IAM service accounts
  • Google Compute Engine (GCE) instances

This backend focuses on identities specific to Google Cloud and does not back up authenticating arbitrary Google or G Suite users or generic OAuth confronting Google.

This plugin is adult in a separate GitHub repository at hashicorp/vault-plugin-auth-gcp, but is automatically bundled in Vault releases. Delight file all feature requests, bugs, and pull requests specific to the GCP plugin under that repository.

»Cosign

»Via the CLI Helper

Vault includes a CLI helper that obtains a signed JWT locally and sends the request to Vault. This helper is merely bachelor for IAM-type roles.

                              $                vault login -method=gcp                  \                                                                              role                  =                  "my-role"                  \                                                                              service_account                  =                  "authenticating-account@my-project.iam.gserviceaccount.com"                  \                                                                              jwt_exp                  =                  "15m"                  \                                                                              credentials                  =@path/to/signer/credentials.json                          
                                                                                                                              $                          vault login -method=gcp                            \                                                                                                                                                                            office                            =                            "my-role"                            \                                                                                                                                                                            service_account                            =                            "authenticating-business relationship@my-project.iam.gserviceaccount.com"                            \                                                                                                                                                                            jwt_exp                            =                            "15m"                            \                                                                                                                                                                            credentials                            =@path/to/signer/credentials.json                                                                                                                  

For more usage information, run vault auth help gcp.

Note: The project parameter has been removed in Vault 1.5.ix+, ane.6.5+, and i.seven.2+. It is no longer needed for configuration and will exist ignored if provided.

»Via the CLI

                              $                vault                  write                  -field=token auth/gcp/login                  \                                                                              role                  =                  "my-role"                  \                                                                              jwt                  =                  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."                                          
                                                                                                                              $                          vault                            write                            -field=token auth/gcp/login                            \                                                                                                                                                                            role                            =                            "my-part"                            \                                                                                                                                                                            jwt                            =                            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."                                                                                                                                            

Run into Generating JWTs for ways to obtain the JWT token.

»Via the API

                              $                                  gyre                  \                                                                              --request Postal service                  \                                                                              --information                  '{"role":"my-role", "jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}'                  \                                                                              http://127.0.0.1:8200/v1/auth/gcp/login                          
                                                                                                                              $                                                      curl                            \                                                                                                                                                                            --request POST                            \                                                                                                                                                                            --data                            '{"role":"my-function", "jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}'                            \                                                                                                                                                                            http://127.0.0.ane:8200/v1/auth/gcp/login                                                                                                                  

Encounter API docs for expected response.

»Configuration

Auth methods must be configured in advance before users or machines can authenticate. These steps are usually completed by an operator or configuration management tool.

  1. Enable the Google Cloud auth method:

  2. Configure the auth method credentials:

    $ vault write auth/gcp/config \                                         credentials=@/path/to/credentials.json                                  
                                                                                                $ vault write auth/gcp/config \                                                                                                            credentials=@/path/to/credentials.json                                                                                                                                          

    If yous are using case credentials or want to specify credentials via an surroundings variable, you tin can skip this step. To learn more, see the Google Cloud Hallmark section beneath.

  3. Create a named role:

    For an iam-blazon role:

    $ vault write auth/gcp/role/my-iam-part \                                         type="iam" \                                         policies="dev,prod" \                                         bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"                                  
                                                                                                $ vault write auth/gcp/role/my-iam-role \                                                                                                            blazon="iam" \                                                                                                            policies="dev,prod" \                                                                                                            bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"                                                                                                                                          

    For a gce-type role:

    $ vault write auth/gcp/role/my-gce-role \                                         type="gce" \                                         policies="dev,prod" \                                         bound_projects="my-project1,my-project2" \                                         bound_zones="us-east1-b" \                                         bound_labels="foo:bar,zip:zap" \                                         bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"                                  
                                                                                                $ vault write auth/gcp/role/my-gce-role \                                                                                                            type="gce" \                                                                                                            policies="dev,prod" \                                                                                                            bound_projects="my-project1,my-project2" \                                                                                                            bound_zones="u.s.a.-east1-b" \                                                                                                            bound_labels="foo:bar,zip:zap" \                                                                                                            bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"                                                                                                                                          

    Note that bound_service_accounts is only required for iam-type roles.

    For the complete list of configuration options for each type, please see the API documentation.

»Authentication

The Google Cloud Vault auth method uses the official Google Deject Golang SDK. This ways information technology supports the common means of providing credentials to Google Cloud.

  1. The environment variable GOOGLE_APPLICATION_CREDENTIALS. This is specified every bit the path to a Google Cloud credentials file, typically for a service account. If this environs variable is present, the resulting credentials are used. If the credentials are invalid, an error is returned.

  2. Default instance credentials. When no environment variable is present, the default service business relationship credentials are used.

For more information on service accounts, please see the Google Cloud Service Accounts documentation.

To use this auth method, the service account must have the post-obit minimum scope:

https://www.googleapis.com/auth/cloud-platform                          
                                                                            https://www.googleapis.com/auth/cloud-platform                                                                                                                  

»Required GCP Permissions

»Vault Server Permissions

For iam-blazon Vault roles, Vault can be given the following roles:

roles/iam.serviceAccountKeyAdmin                          
                                                                            roles/iam.serviceAccountKeyAdmin                                                                                                                  

For gce-type Vault roles, Vault can exist given the following roles:

If you instead wish to create a custom role with only the exact GCP permissions required, utilize the following list of permissions:

iam.serviceAccounts.go                             iam.serviceAccountKeys.get                             compute.instances.get                             compute.instanceGroups.list                          
                                                                            iam.serviceAccounts.get                                                                    iam.serviceAccountKeys.get                                                                    compute.instances.become                                                                    compute.instanceGroups.list                                                                                                                  

These allow Vault to:

  • verify the service account, either directly authenticating or associated with authenticating GCE instance, exists
  • get the corresponding public keys for verifying JWTs signed past service account private keys.
  • verify authenticating GCE instances exist
  • compare leap fields for GCE roles (zone/region, labels, or membership in given instance groups)

If you are using Grouping Aliases as described below, you volition also need to add the resourcemanager.projects.get permission.

»Permissions For Authenticating Against Vault

Note that the previously mentioned permissions are given to the Vault servers. The IAM service account or GCE instance that is authenticating against Vault must have the post-obit office:

roles/iam.serviceAccountTokenCreator                          
                                                                            roles/iam.serviceAccountTokenCreator                                                                                                                  

Warning: Make sure this role is only applied then your service account can impersonate itself. If this role is applied GCP project-wide, this will allow the service account to impersonate whatever service account in the GCP project where it resides. Run across Managing service account impersonation for more information.

»Group Aliases

As of Vault 1.0, roles can specify an add_group_aliases boolean parameter that adds group aliases to the auth response. These aliases can assistance in edifice reusable policies since they are available as interpolated values in Vault's policy engine. Once enabled, the auth response will include the following aliases:

              [                                          "project-$PROJECT_ID"              ,                                          "folder-$SUBFOLDER_ID"              ,                                          "folder-$FOLDER_ID"              ,                                          "organisation-$ORG_ID"              ]            
                                                                                                    [                                                                    "project-$PROJECT_ID"                        ,                                                                    "folder-$SUBFOLDER_ID"                        ,                                                                    "binder-$FOLDER_ID"                        ,                                                                    "organization-$ORG_ID"                                                                    ]                                                                                          

If y'all are using a custom role for Vault server, you will need to add the resourcemanager.projects.get permission to your custom role.

»Implementation Details

This department describes the implementation details for how Vault communicates with Google Deject to authenticate and qualify JWT tokens. This information is provided for those who are curious, but these details are not required knowledge for using the auth method.

»IAM Login

IAM login applies only to roles of blazon iam. The Vault authentication workflow for IAM service accounts looks similar this:

Vault Google Cloud IAM Login Workflow

  1. The client generates a signed JWT using the Service Account Credentials projects.serviceAccounts.signJwt API method. For examples of how to do this, come across the Generating JWTs section.

  2. The client sends this signed JWT to Vault forth with a part name.

  3. Vault extracts the kid header value, which contains the ID of the key-pair used to generate the JWT, and the sub ID/email to find the service account key. If the service account does not exist or the primal is not linked to the service account, Vault denies authentication.

  4. Vault authorizes the confirmed service account against the given role. If that is successful, a Vault token with the proper policies is returned.

»GCE Login

GCE login only applies to roles of blazon gce and must be completed on an instance running in GCE. These steps will not piece of work from your local laptop or another cloud provider.

Vault Google Cloud GCE Login Workflow

  1. The client obtains an example identity metadata token on a GCE case.

  2. The customer sends this JWT to Vault along with a role name.

  3. Vault extracts the kid header value, which contains the ID of the key-pair used to generate the JWT, to find the OAuth2 public cert to verify this JWT.

  4. Vault authorizes the confirmed instance confronting the given role, ensuring the instance matches the leap zones, regions, or instance groups. If that is successful, a Vault token with the proper policies is returned.

»Generating JWTs

This department details the various methods and examples for obtaining JWT tokens.

»Service Account Credentials API

This describes how to use the GCP Service Account Credentials API method directly to generate the signed JWT with the claims that Vault expects. Notation the CLI does this process for you and is much easier, and that in that location is very footling reason to exercise this yourself.

»curl Case

Vault requires the following minimum claim set:

              {                                          "sub"              :              "$SERVICE_ACCOUNT_EMAIL_OR_ID"              ,                                          "aud"              :              "vault/$ROLE"              ,                                          "exp"              :              "$EXPIRATION"              }            
                                                                                                    {                                                                    "sub"                        :                        "$SERVICE_ACCOUNT_EMAIL_OR_ID"                        ,                                                                    "aud"                        :                        "vault/$ROLE"                        ,                                                                    "exp"                        :                        "$EXPIRATION"                                                                    }                                                                                          

For the API method, providing the expiration claim exp is required. If it is omitted, information technology volition not be added automatically and Vault will deny hallmark. Expiration must be specified as a NumericDate value (seconds from Epoch). This value must exist earlier the max JWT expiration allowed for a function. This defaults to 15 minutes and cannot be more than 1 60 minutes.

One you have all this information, the JWT token tin can be signed using curl and oauth2l:

Office="my-role"                             SERVICE_ACCOUNT="service-account@my-project.iam.gserviceaccount.com"                             OAUTH_TOKEN="$(oauth2l header cloud-platform)"                             EXPIRATION="<your_token_expiration>"                             JWT_CLAIM="{\\\"aud\\\":\\\"vault/${ROLE}\\\", \\\"sub\\\": \\\"${SERVICE_ACCOUNT}\\\", \\\"exp\\\": ${EXPIRATION}}"                                            curl \                               --header "${OAUTH_TOKEN}" \                               --header "Content-Type: application/json" \                               --asking Mail \                               --data "{\"payload\": \"${JWT_CLAIM}\"}" \                               "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${SERVICE_ACCOUNT}:signJwt"                          
                                                                            ROLE="my-role"                                                                    SERVICE_ACCOUNT="service-business relationship@my-project.iam.gserviceaccount.com"                                                                    OAUTH_TOKEN="$(oauth2l header cloud-platform)"                                                                    EXPIRATION="<your_token_expiration>"                                                                    JWT_CLAIM="{\\\"aud\\\":\\\"vault/${Part}\\\", \\\"sub\\\": \\\"${SERVICE_ACCOUNT}\\\", \\\"exp\\\": ${EXPIRATION}}"                                                                                                                curl \                                                                                            --header "${OAUTH_TOKEN}" \                                                                                            --header "Content-Type: application/json" \                                                                                            --request POST \                                                                                            --data "{\"payload\": \"${JWT_CLAIM}\"}" \                                                                                            "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${SERVICE_ACCOUNT}:signJwt"                                                                                                                  

»gcloud Example

You lot can besides practice this through the (currently beta) gcloud command. Note that you will exist required to provide the expiration claim exp as a part of the JWT input to the command.

                              $                gcloud beta iam service-accounts sign-jwt                  $INPUT_JWT_CLAIMS                  $OUTPUT_JWT_FILE                  \                                                                              --iam-business relationship=service-business relationship@my-project.iam.gserviceaccount.com                  \                                                                              --project=my-project                          
                                                                                                                              $                          gcloud beta iam service-accounts sign-jwt                            $INPUT_JWT_CLAIMS                            $OUTPUT_JWT_FILE                            \                                                                                                                                                                            --iam-account=service-account@my-projection.iam.gserviceaccount.com                            \                                                                                                                                                                            --project=my-project                                                                                                                  

»Golang Example

Read more than on the Google Open Source web log.

»GCE

GCE tokens can just exist generated from a GCE instance. The JWT token tin be obtained from the service-accounts/default/identity endpoint for a instance's metadata server.

»curlicue Instance

Function="my-gce-role"                                            curl \                               --header "Metadata-Flavor: Google" \                               --go \                               --data-urlencode "audience=http://vault/${ROLE}" \                               --data-urlencode "format=full" \                               "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity"                          
                                                                            Role="my-gce-role"                                                                                                                gyre \                                                                                            --header "Metadata-Flavour: Google" \                                                                                            --go \                                                                                            --data-urlencode "audience=http://vault/${ROLE}" \                                                                                            --data-urlencode "format=total" \                                                                                            "http://metadata/computeMetadata/v1/case/service-accounts/default/identity"                                                                                                                  

»API

The GCP Auth Plugin has a full HTTP API. Please run across the API docs for more than details.

»Lawmaking Example

The following code snippet demonstrates the Google Cloud auth method to authenticate with Vault.

                package                primary                                                 import                (                                                "context"                                                "fmt"                                                "os"                                                     vault                "github.com/hashicorp/vault/api"                                    auth                "github.com/hashicorp/vault/api/auth/gcp"                )                                                   func                getSecretWithGCPAuthIAM                (                )                (                string                ,                error                )                {                                    config                :=                vault.                DefaultConfig                (                )                                                      client,                err                :=                vault.                NewClient                (config)                                                if                err                !=                nil                {                                                return                ""                ,                fmt.                Errorf                (                "unable to initialize Vault client: %west"                ,                err)                                                }                                                                                                                                                     if                pathToCreds                :=                bone.                Getenv                (                "GOOGLE_APPLICATION_CREDENTIALS"                )                ;                pathToCreds                ==                ""                {                                        fmt.                Printf                (                "WARNING: Environment variable GOOGLE_APPLICATION_CREDENTIALS was not prepare. IAM client for JWT signing and Vault server IAM customer will both fall back to default case credentials.\n"                )                                                }                                                     svcAccountEmail                :=                fmt.                Sprintf                (                "%s@%s.iam.gserviceaccount.com"                ,                os.                Getenv                (                "GCP_SERVICE_ACCOUNT_NAME"                )                ,                os.                Getenv                (                "GOOGLE_CLOUD_PROJECT"                )                )                                                                                                                    gcpAuth,                err                :=                auth.                NewGCPAuth                (                                                "dev-role-iam"                ,                                        auth.                WithIAMAuth                (svcAccountEmail)                ,                                                )                                                if                err                !=                nil                {                                                return                ""                ,                fmt.                Errorf                (                "unable to initialize GCP auth method: %w"                ,                err)                                                }                                                     authInfo,                err                :=                client.                Auth                (                )                .                Login                (context.                TODO                (                )                ,                gcpAuth)                                                if                err                !=                zero                {                                                return                ""                ,                fmt.                Errorf                (                "unable to login to GCP auth method: %w"                ,                err)                                                }                                                if                authInfo                ==                nil                {                                                return                ""                ,                fmt.                Errorf                (                "login response did non return customer token"                )                                                }                                                                          hush-hush,                err                :=                client.                Logical                (                )                .                Read                (                "kv-v2/information/creds"                )                                                if                err                !=                nil                {                                                return                ""                ,                fmt.                Errorf                (                "unable to read secret: %due west"                ,                err)                                                }                                                     information,                ok                :=                secret.Data[                "data"                ]                .                (                map                [                string                ]                interface                {                }                )                                                if                !ok                {                                                return                ""                ,                fmt.                Errorf                (                "data type assertion failed: %T %#v"                ,                secret.Data[                "data"                ]                ,                secret.Data[                "data"                ]                )                                                }                                                                                               key                :=                "countersign"                                    value,                ok                :=                data[fundamental]                .                (                string                )                                                if                !ok                {                                                return                ""                ,                fmt.                Errorf                (                "value type assertion failed: %T %#v"                ,                information[key]                ,                data[key]                )                                                }                                                                 return                value,                nil                }                                              
                                                            1                                            two                                            iii                                            iv                                            5                                            6                                            7                                            8                                            9                                            x                      11                      12                      thirteen                      fourteen                      15                      16                      17                      xviii                      19                      20                      21                      22                      23                      24                      25                      26                      27                      28                      29                      30                      31                      32                      33                      34                      35                      36                      37                      38                      39                      40                      41                      42                      43                      44                      45                      46                      47                      48                      49                      50                      51                      52                      53                      54                      55                      56                      57                      58                      59                      60                      61                      62                      63                      64                      65                      66                      67                      68                      69                      seventy                      71                      72                      73                                                                                                                package                          main                                                                                                                                                    import                          (                                                                          "context"                                                                          "fmt"                                                                          "os"                                                                                                                          vault                          "github.com/hashicorp/vault/api"                                                                          auth                          "github.com/hashicorp/vault/api/auth/gcp"                                                                          )                                                                                                                          // Fetches a central-value secret (kv-v2) after authenticating to Vault                                                                          // via GCP IAM, one of ii auth methods used to authenticate with                                                                          // GCP (the other is GCE auth).                                                                          func                          getSecretWithGCPAuthIAM                          (                          )                          (                          cord                          ,                          error                          )                          {                                                                          config                          :=                          vault.                          DefaultConfig                          (                          )                          // alter for more granular configuration                                                                                                                          customer,                          err                          :=                          vault.                          NewClient                          (config)                                                                          if                          err                          !=                          nil                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "unable to initialize Vault client: %due west"                          ,                          err)                                                                          }                                                                                                                          // For IAM-style auth, the environment variable GOOGLE_APPLICATION_CREDENTIALS                                                                          // must be set with the path to a valid credentials JSON file, otherwise                                                                          // Vault volition fall back to Google's default instance credentials.                                                                          // Acquire about authenticating to GCS with service account credentials at https://cloud.google.com/docs/authentication/production                                                                          if                          pathToCreds                          :=                          os.                          Getenv                          (                          "GOOGLE_APPLICATION_CREDENTIALS"                          )                          ;                          pathToCreds                          ==                          ""                          {                                                                          fmt.                          Printf                          (                          "WARNING: Environment variable GOOGLE_APPLICATION_CREDENTIALS was not gear up. IAM customer for JWT signing and Vault server IAM customer will both autumn dorsum to default instance credentials.\n"                          )                                                                          }                                                                                                                          svcAccountEmail                          :=                          fmt.                          Sprintf                          (                          "%south@%due south.iam.gserviceaccount.com"                          ,                          os.                          Getenv                          (                          "GCP_SERVICE_ACCOUNT_NAME"                          )                          ,                          os.                          Getenv                          (                          "GOOGLE_CLOUD_PROJECT"                          )                          )                                                                                                                          // We pass the auth.WithIAMAuth choice to use the IAM-style authentication                                                                          // of the GCP auth backend. Otherwise, nosotros default to using GCE-style                                                                          // hallmark, which gets its credentials from the metadata server.                                                                          gcpAuth,                          err                          :=                          auth.                          NewGCPAuth                          (                                                                          "dev-role-iam"                          ,                                                                          auth.                          WithIAMAuth                          (svcAccountEmail)                          ,                                                                          )                                                                          if                          err                          !=                          cipher                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "unable to initialize GCP auth method: %w"                          ,                          err)                                                                          }                                                                                                                          authInfo,                          err                          :=                          client.                          Auth                          (                          )                          .                          Login                          (context.                          TODO                          (                          )                          ,                          gcpAuth)                                                                          if                          err                          !=                          nil                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "unable to login to GCP auth method: %west"                          ,                          err)                                                                          }                                                                          if                          authInfo                          ==                          nil                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "login response did not render customer token"                          )                                                                          }                                                                                                                          // go hush-hush                                                                          hole-and-corner,                          err                          :=                          client.                          Logical                          (                          )                          .                          Read                          (                          "kv-v2/data/creds"                          )                                                                          if                          err                          !=                          cipher                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "unable to read surreptitious: %w"                          ,                          err)                                                                          }                                                                                                                          data,                          ok                          :=                          secret.Information[                          "data"                          ]                          .                          (                          map                          [                          string                          ]                          interface                          {                          }                          )                                                                          if                          !ok                          {                                                                          return                          ""                          ,                          fmt.                          Errorf                          (                          "information type exclamation failed: %T %#v"                          ,                          secret.Data[                          "data"                          ]                          ,                          secret.Data[                          "data"                          ]                          )                                                                          }                                                                                                                          // data map can comprise more one key-value pair,                                                                          // in this example we're just grabbing one of them                                                                          key                          :=                          "password"                                                                          value,                          ok                          :=                          data[key]                          .                          (                          string                          )                                                                          if                          !ok                          {                                                                          render                          ""                          ,                          fmt.                          Errorf                          (                          "value type assertion failed: %T %#5"                          ,                          data[fundamental]                          ,                          data[key]                          )                                                                          }                                                                                                                          return                          value,                          nil                                                                          }                                                                                                                                                    
                using                Arrangement                ;                using                System.Collections.Generic                ;                using                Organisation.IO                ;                using                Organisation.Threading.Tasks                ;                using                Google.Apis.Auth.OAuth2                ;                using                Google.Apis.Services                ;                using                Google.Apis.Iam.v1                ;                using                Newtonsoft.Json                ;                using                VaultSharp                ;                using                VaultSharp.V1.AuthMethods                ;                using                VaultSharp.V1.AuthMethods.GoogleCloud                ;                using                VaultSharp.V1.Commons                ;                                                using                Information                =                Google.Apis.Iam.v1.Data                ;                                                namespace                Examples                {                                                public                class                GCPAuthExample                                                                 {                                                                                                                                                    public                                  cord                                GetSecretGcp                (                )                                                {                                                                  var                                vaultAddr                =                Environment.                GetEnvironmentVariable                (                "VAULT_ADDR"                )                ;                                                if                (String.                IsNullOrEmpty                (vaultAddr)                )                                                {                                                throw                new                Organization.ArgumentNullException                (                "Vault Accost"                )                ;                                                }                                                                                   var                                roleName                =                Surroundings.                GetEnvironmentVariable                (                "VAULT_ROLE"                )                ;                                                if                (String.                IsNullOrEmpty                (roleName)                )                                                {                                                throw                new                System.ArgumentNullException                (                "Vault Role Name"                )                ;                                                }                                                                                              if                (String.                IsNullOrEmpty                (Surround.                GetEnvironmentVariable                (                "GOOGLE_APPLICATION_CREDENTIALS"                )                )                )                                                {                                                Console.                WriteLine                (                "Warning: Environment variable GOOGLE_APPLICATION_CREDENTIALS was not fix. IAM client for JWT signing will autumn dorsum to default instance credentials."                )                ;                                                }                                                                                   var                                jwt                =                SignJWT                (                )                ;                                                                                  IAuthMethodInfo                authMethod                =                new                GoogleCloudAuthMethodInfo                (roleName,                jwt)                ;                                                                  var                                vaultClientSettings                =                new                VaultClientSettings                (vaultAddr,                authMethod)                ;                                                                 IVaultClient                vaultClient                =                new                VaultClient                (vaultClientSettings)                ;                                                                                                               Secret<SecretData>                                kv2Secret                =                nothing                ;                                            kv2Secret                =                vaultClient.V1.Secrets.KeyValue.V2.                ReadSecretAsync                (                path                :                "/creds"                )                .Result;                                                                                                               var                                countersign                =                kv2Secret.Data.Data[                "password"                ]                ;                                                                                             return                password.                ToString                (                )                ;                                                }                                                                                                                                            private                                  string                                SignJWT                (                )                                                {                                                                  var                                roleName                =                Surroundings.                GetEnvironmentVariable                (                "GCP_ROLE"                )                ;                                                                  var                                svcAcctName                =                Environs.                GetEnvironmentVariable                (                "GCP_SERVICE_ACCOUNT_NAME"                )                ;                                                                  var                                gcpProjName                =                Environment.                GetEnvironmentVariable                (                "GOOGLE_CLOUD_PROJECT"                )                ;                                                                 IamService                iamService                =                new                IamService                (                new                BaseClientService.Initializer                                                {                                                HttpClientInitializer                =                GetCredential                (                )                ,                                                ApplicationName                =                "Google-iamSample/0.1"                ,                                                }                )                ;                                                                                   string                                svcEmail                =                                  $"                                      {                    svcAcctName                    }                                    @                                      {                    gcpProjName                    }                                    .iam.gserviceaccount.com"                                ;                                                                  cord                                proper noun                =                                  $"projects/-/serviceAccounts/                                      {                    svcEmail                    }                                    "                                ;                                                                                  TimeSpan                currentTime                =                (DateTime.UtcNow                -                new                DateTime                (                1970                ,                ane                ,                1                )                )                ;                                                                  int                                expiration                =                (                int                )                (currentTime.TotalSeconds)                +                900                ;                                                                 Data.SignJwtRequest                requestBody                =                new                Data.SignJwtRequest                (                )                ;                                            requestBody.Payload                =                JsonConvert.                SerializeObject                (                new                Dictionary<                  string                  ,                  object                  >                                (                )                                                {                                                {                "aud"                ,                                  $"vault/                                      {                    roleName                    }                                    "                                }                ,                                                {                "sub"                ,                svcEmail                }                ,                                                {                "exp"                ,                expiration                }                                                }                )                ;                                                                 ProjectsResource.ServiceAccountsResource.SignJwtRequest                asking                =                iamService.Projects.ServiceAccounts.                SignJwt                (requestBody,                name)                ;                                                                 Data.SignJwtResponse                response                =                request.                Execute                (                )                ;                                                                                             return                JsonConvert.                SerializeObject                (response.SignedJwt)                .                Supplant                (                "\""                ,                ""                )                ;                                                }                                                                 public                static                GoogleCredential                GetCredential                (                )                                                {                                                GoogleCredential                credential                =                Chore.                Run                (                (                )                =>                GoogleCredential.                GetApplicationDefaultAsync                (                )                )                .Result;                                                if                (credential.IsCreateScopedRequired)                                                {                                                credential                =                credential.                CreateScoped                (                "https://www.googleapis.com/auth/cloud-platform"                )                ;                                                }                                                return                credential;                                                }                                                }                }              
                                                            1                                            2                                            three                                            iv                                            five                                            vi                                            7                                            eight                                            9                                            ten                                            eleven                                            12                                            13                                            14                                            15                                            16                                            17                                            eighteen                                            19                                            twenty                                            21                                            22                                            23                                            24                                            25                                            26                                            27                                            28                                            29                                            30                                            31                                            32                                            33                                            34                                            35                                            36                                            37                                            38                                            39                                            40                                            41                                            42                                            43                                            44                                            45                                            46                                            47                                            48                                            49                                            l                                            51                                            52                                            53                                            54                                            55                                            56                                            57                                            58                                            59                                            60                                            61                                            62                                            63                                            64                                            65                                            66                                            67                                            68                                            69                                            70                                            71                                            72                                            73                                            74                                            75                                            76                                            77                                            78                                            79                                            lxxx                                            81                                            82                                            83                                            84                                            85                                            86                                            87                                            88                                            89                                            90                                            91                                            92                                            93                                            94                                            95                                            96                                            97                                            98                                            99                                            100                      101                      102                      103                      104                      105                      106                                                                                                                using                          System                          ;                                                                          using                          System.Collections.Generic                          ;                                                                          using                          System.IO                          ;                                                                          using                          System.Threading.Tasks                          ;                                                                          using                          Google.Apis.Auth.OAuth2                          ;                                                                          using                          Google.Apis.Services                          ;                                                                          using                          Google.Apis.Iam.v1                          ;                                                                          using                          Newtonsoft.Json                          ;                                                                          using                          VaultSharp                          ;                                                                          using                          VaultSharp.V1.AuthMethods                          ;                                                                          using                          VaultSharp.V1.AuthMethods.GoogleCloud                          ;                                                                          using                          VaultSharp.V1.Commons                          ;                                                                                                                          using                          Data                          =                          Google.Apis.Iam.v1.Information                          ;                                                                                                                          namespace                          Examples                                                                          {                                                                          public                          class                          GCPAuthExample                                                                                                                              {                                                                          ///                                                                                          <summary                              >                                                                                                                                /// Fetches a key-value secret (kv-v2) afterward authenticating to Vault via GCP IAM,                                                                          /// ane of two auth methods used to cosign with GCP (the other is GCE auth).                                                                          ///                                                                                          </summary                              >                                                                                                                                public                                                      string                                                    GetSecretGcp                          (                          )                                                                          {                                                                                                      var                                                    vaultAddr                          =                          Environment.                          GetEnvironmentVariable                          (                          "VAULT_ADDR"                          )                          ;                                                                          if                          (String.                          IsNullOrEmpty                          (vaultAddr)                          )                                                                          {                                                                          throw                          new                          System.ArgumentNullException                          (                          "Vault Address"                          )                          ;                                                                          }                                                                                                                                                      var                                                    roleName                          =                          Environment.                          GetEnvironmentVariable                          (                          "VAULT_ROLE"                          )                          ;                                                                          if                          (String.                          IsNullOrEmpty                          (roleName)                          )                                                                          {                                                                          throw                          new                          System.ArgumentNullException                          (                          "Vault Role Proper noun"                          )                          ;                                                                          }                                                                                                                          // Larn about authenticating to GCS with service account credentials at https://cloud.google.com/docs/authentication/production                                                                          if                          (String.                          IsNullOrEmpty                          (Environment.                          GetEnvironmentVariable                          (                          "GOOGLE_APPLICATION_CREDENTIALS"                          )                          )                          )                                                                          {                                                                          Console.                          WriteLine                          (                          "WARNING: Environment variable GOOGLE_APPLICATION_CREDENTIALS was not set. IAM client for JWT signing will fall back to default instance credentials."                          )                          ;                                                                          }                                                                                                                                                      var                                                    jwt                          =                          SignJWT                          (                          )                          ;                                                                                                                                                                              IAuthMethodInfo                          authMethod                          =                          new                          GoogleCloudAuthMethodInfo                          (roleName,                          jwt)                          ;                                                                                                      var                                                    vaultClientSettings                          =                          new                          VaultClientSettings                          (vaultAddr,                          authMethod)                          ;                                                                                                                          IVaultClient                          vaultClient                          =                          new                          VaultClient                          (vaultClientSettings)                          ;                                                                                                                                                                              // We tin call up the cloak-and-dagger subsequently creating our VaultClient object                                                                          Secret<SecretData>                                                    kv2Secret                          =                          null                          ;                                                                          kv2Secret                          =                          vaultClient.V1.Secrets.KeyValue.V2.                          ReadSecretAsync                          (                          path                          :                          "/creds"                          )                          .Issue;                                                                                                                                                                                                          var                                                    password                          =                          kv2Secret.Data.Information[                          "password"                          ]                          ;                                                                                                                                                                              return                          password.                          ToString                          (                          )                          ;                                                                          }                                                                                                                          ///                                                                                          <summary                              >                                                                                                                                /// Generate signed JWT from GCP IAM                                                                          ///                                                                                          </summary                              >                                                                                                                                private                                                      string                                                    SignJWT                          (                          )                                                                          {                                                                                                      var                                                    roleName                          =                          Environment.                          GetEnvironmentVariable                          (                          "GCP_ROLE"                          )                          ;                                                                                                      var                                                    svcAcctName                          =                          Environment.                          GetEnvironmentVariable                          (                          "GCP_SERVICE_ACCOUNT_NAME"                          )                          ;                                                                                                      var                                                    gcpProjName                          =                          Environment.                          GetEnvironmentVariable                          (                          "GOOGLE_CLOUD_PROJECT"                          )                          ;                                                                                                                          IamService                          iamService                          =                          new                          IamService                          (                          new                          BaseClientService.Initializer                                                                          {                                                                          HttpClientInitializer                          =                          GetCredential                          (                          )                          ,                                                                          ApplicationName                          =                          "Google-iamSample/0.one"                          ,                                                                          }                          )                          ;                                                                                                                                                      string                                                    svcEmail                          =                                                      $"                                                          {                              svcAcctName                              }                                                        @                                                          {                              gcpProjName                              }                                                        .iam.gserviceaccount.com"                                                    ;                                                                                                      string                                                    proper noun                          =                                                      $"projects/-/serviceAccounts/                                                          {                              svcEmail                              }                                                        "                                                    ;                                                                                                                                                                              TimeSpan                          currentTime                          =                          (DateTime.UtcNow                          -                          new                          DateTime                          (                          1970                          ,                          1                          ,                          1                          )                          )                          ;                                                                                                      int                                                    expiration                          =                          (                          int                          )                          (currentTime.TotalSeconds)                          +                          900                          ;                                                                                                                          Information.SignJwtRequest                          requestBody                          =                          new                          Data.SignJwtRequest                          (                          )                          ;                                                                          requestBody.Payload                          =                          JsonConvert.                          SerializeObject                          (                          new                          Dictionary<                            string                            ,                            object                            >                                                    (                          )                                                                          {                                                                          {                          "aud"                          ,                                                      $"vault/                                                          {                              roleName                              }                                                        "                                                    }                          ,                                                                          {                          "sub"                          ,                          svcEmail                          }                          ,                                                                          {                          "exp"                          ,                          expiration                          }                                                                          }                          )                          ;                                                                                                                          ProjectsResource.ServiceAccountsResource.SignJwtRequest                          request                          =                          iamService.Projects.ServiceAccounts.                          SignJwt                          (requestBody,                          name)                          ;                                                                                                                          Data.SignJwtResponse                          response                          =                          request.                          Execute                          (                          )                          ;                                                                                                                                                                              return                          JsonConvert.                          SerializeObject                          (response.SignedJwt)                          .                          Supersede                          (                          "\""                          ,                          ""                          )                          ;                                                                          }                                                                                                                          public                          static                          GoogleCredential                          GetCredential                          (                          )                                                                          {                                                                          GoogleCredential                          credential                          =                          Task.                          Run                          (                          (                          )                          =>                          GoogleCredential.                          GetApplicationDefaultAsync                          (                          )                          )                          .Event;                                                                          if                          (credential.IsCreateScopedRequired)                                                                          {                                                                          credential                          =                          credential.                          CreateScoped                          (                          "https://www.googleapis.com/auth/cloud-platform"                          )                          ;                                                                          }                                                                          render                          credential;                                                                          }                                                                          }                                                                          }                                                                                                    

logantheive.blogspot.com

Source: https://www.vaultproject.io/docs/auth/gcp

Share this post

0 Response to "Unable to Read Gcloud Auth Activate-service-account --key-file=[path]"

Postar um comentário

Postagem mais recente Postagem mais antiga Página inicial
Assinar: Postar comentários (Atom)

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel

Popular Post

  • 15 Most Stunning Mohawk Braids for Black Women
    A mohawk braid is a protective hairstyle for black women where the pilus is braided from the sides towards the middle of t...
  • Pirates of the Caribbean Theme Piano Easy Musescore
    Home PRINTABLE TEMPLATES Free Printable Pirates Of The Ca...
  • If F is Continuous and Integral From 1 to 8 F X Dx 15
    Introduction to Integral Calculator Our Advanced Integral calculator is the most comprehensive integral solution o...



banner



Copyright - Logan Theive