The most comprehensive cross-platform .NET Library for HashiCorp's Vault - A Secret Management System.
VaultSharp Latest Documentation: Inline Below and also at: https://rajanadar.github.io/VaultSharp/
VaultSharp Questions/Clarifications:Ask on Stack Overflow with the tag vaultsharp
VaultSharp Gitter Lobby:Gitter Lobby
Report Issues/Feedback:Create a VaultSharp GitHub issue
Contributing Guidlines:VaultSharp Contribution Guidelines
- VaultSharp is a .NET Standard 1.3, .NET Standard 2.0, .NET Standard 2.1, .NET Framework 4.5, .NET Framework 4.6.x, .NET Framework 4.7.x, .NET Framework 4.8, .NET 5.0, .NET 6.0, .NET 7.0 and .NET 8.0 based cross-platform C# Library that can be used in any .NET application to interact with Hashicorp's Vault.
- The Vault system is a secret management system built as an Http Service by Hashicorp.
VaultSharp has been re-designed ground up, to give a structured user experience across the various auth methods, secrets engines & system apis. Also, the Intellisense on IVaultClient class should help. I have tried to add a lot of documentation.
- Add a Nuget reference to VaultSharp as follows
Install-Package VaultSharp -Version <latest_version> - Instantiate a IVaultClient as follows:
// Initialize one of the several auth methods.IAuthMethodInfoauthMethod=newTokenAuthMethodInfo("MY_VAULT_TOKEN");// Initialize settings. You can also set proxies, custom delegates etc. here.varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// Use client to read a key-value secret.// Very important to provide mountpath and secret name as two separate parameters. Don't provide a single combined string.// Please use named parameters for 100% clarity of code. (the method also takes version and wrapTimeToLive as params)Secret<SecretData>kv2Secret=awaitvaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path:"secretPath",mountPoint:"mountPointIfNotDefault");// Generate a dynamic Consul credentialSecret<ConsulCredentials>consulCreds=awaitvaultClient.V1.Secrets.Consul.GetCredentialsAsync(consulRole,consulMount);stringconsulToken=consulCreds.Data.Token;- VaultSharp supports
- All the Auth Methods for Logging into Vault. (AppRole, AWS, Azure, GitHub, Google Cloud, JWT/OIDC, Kubernetes, LDAP, Okta, RADIUS, TLS, Tokens & UserPass)
- All the secret engines to get dynamic credentials. (AD, AWS EC2 and IAM, Consul, Cubbyhole, Databases, Google Cloud, Key-Value, Nomad, PKI, RabbitMQ, SSH and TOTP)
- Several system APIs including enterprise vault apis
- You can also bring your own "Auth Method" by providing a custom delegate to fetch a token from anywhere.
- VaultSharp has first class support for Consul engine.
- KeyValue engine supports both v1 and v2 apis.
- Abundant intellisense.
- Provides hooks into http-clients to set custom proxy settings etc.
VaultSharp is built on .NET Standard 1.3 & .NET Standard 2.0 & .NET Standard 2.1 & .NET Frameworks 4.5, 4.6.x, 4.7.x, 4.8 & .NET 5, .NET 6, .NET 7, .NET 8. This makes it highly compatible and cross-platform.
The following implementations are supported due to that.
- .NET Core 1.x, 2.x, 3.x
- .NET Framework 4.5, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2 and 4.8
- .NET 5.0
- .NET 6.0
- .NET 7.0
- .NET 8.0
- Mono 4.x and above
- Xamarin.iOS 10.x and above
- Xamarin Mac 3.x and above
- Xamarin.Android 7.x and above
- UWP 10.x and above
Source: https://github.com/dotnet/standard/blob/master/docs/versions.md
VaultSharp will follow the .NET EOL dates mentioned here:
- https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-framework
- https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core
- https://learn.microsoft.com/en-us/dotnet/standard/frameworks#supported-target-frameworks
- VaultSharp supports dynamic Consul credential generation.
- Please look at the API usage in the 'Consul' section of 'Secrets Engines' below, to see all the Consul related methods in action.
- VaultSharp DOES NOT support automatic token refresh.
- It is the responsibility of the host application to refresh the login token as per its expiry.
- The host app is free to use the
vaultClient.V1.Auth.ResetVaultToken();method to refresh the token from time to time. - The host app is also free to re-initialize the entire
VaultClientinstance. This is helpful when you use AWS Signatures etc. where even if you try to just reset the vault token, it may fail because the signature time is pretty old. In those cases, feel free to re-initialize the whole vaultclient instance
- If the vault login token expiry is way more than the deployment cadence of your application, then the recommended lifetime scope for VaultSharp's IVaultClient is
Singleton. This is because, it will login only once to Vault to get the auth token and use it for the rest of all the vault calls you make. - The only use-case when the
Singletonlifetime will fail you is if your login token expiry is less than your application's deployment cadence. In that case, you have to either write your automatic token renewal logic OR use aRequestScopedlifetime for DI. Renewal logic is more performant than request scoping. This is because, you wouldn't want vaultsharp to request a login token for every web request of yours.
- VaultSharp DOES NOT support built-in client-side failover either by supporting multiple endpoint URI's or by supporting roundrobin DNS.
- I repeat, it DOES NOT.
- It works off a single URL that you provide. Any sort of fail-over etc. needs to be done by you.
- You are free to instantiate a new instance of VaultClient with a different URI.
- By DEFAULT, VaultSharp performs a lazy login to Vault.
- What this means is that, once you initialize VaultSharp with AuthInfo, VaultSharp will not try to immediately login into Vault.
- It'll attempt to login to Vault, only when the first real functional operation is requested. E.g. ReadSecretAsync etc.
- This has the pro that the acquired token can live as long as possible.
- The downside to this is that, any login issues will be a non-app startup discovery (assuming VaultClient is initialized at app startup) which may be not desirable at all. Folks may want to know that Vault Login failed as early as possible.
- VaultSharp now supports this feature starting version 1.6.0.3
- Imemdiately after initializing vault client, invoke the login method to force a login.
IVaultClientvaultClient=newVaultClient(vaultClientSettings);vaultClient.V1.Auth.PerformImmediateLogin();- Please note that this will not work for Token Authentication since you already have a vault token.
- VaultSharp supports all authentication methods supported by the Vault Service
- Here is a sample to instantiate the vault client with each of the authentication backends.
// setup the AliCloud based auth to get the right token.IAuthMethodInfoauthMethod=newAliCloudAuthMethodInfo(roleName,base64EncodedIdentityRequestUrl,base64EncodedIdentityRequestHeaders);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the AliCloud jwt// setup the AppRole based auth to get the right token.IAuthMethodInfoauthMethod=newAppRoleAuthMethodInfo(roleId,secretId);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the app role and secret id.AWS Auth method has 2 flavors. An EC2 way and an IAM way. Here are examples for both.
// setup the AWS-EC2 based auth to get the right token.IAuthMethodInfoauthMethod=newEC2AWSAuthMethodInfo(pkcs7,null,null,nonce,roleName);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the aws-ec2 role// setup the AWS-EC2 based auth to get the right token.IAuthMethodInfoauthMethod=newEC2AWSAuthMethodInfo(null,identity,signature,nonce,roleName);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the aws-ec2 role// setup the AWS-IAM based auth to get the right token.// Step 1: Pull the following NuGet Packages// 1. AWSSDK.Core// 2. AWSSDK.SecurityToken// Step 2: Boiler-plate code to generate the Signed AWS STS Headers.varamazonSecurityTokenServiceConfig=newAmazonSecurityTokenServiceConfig();// If you are running VaultSharp on a real EC2 instance, use the following line of code.// var awsCredentials = new InstanceProfileAWSCredentials();// If you are running VaultSharp on a non-EC2 instance like local dev boxes or non-AWS environment, use the following line of code.AWSCredentialsawsCredentials=newStoredProfileAWSCredentials();// picks up the credentials from your profile.// AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey: "YOUR_ACCESS_KEY", secretKey: "YOUR_SECRET_KEY"); // explicit credentialsvariamRequest=GetCallerIdentityRequestMarshaller.Instance.Marshall(newGetCallerIdentityRequest());iamRequest.Endpoint=newUri(amazonSecurityTokenServiceConfig.DetermineServiceURL());iamRequest.ResourcePath="/";iamRequest.Headers.Add("User-Agent","https://github.com/rajanadar/vaultsharp/0.11.1000");iamRequest.Headers.Add("X-Amz-Security-Token",awsCredentials.GetCredentials().Token);iamRequest.Headers.Add("Content-Type","application/x-www-form-urlencoded; charset=utf-8");newAWS4Signer().Sign(iamRequest,amazonSecurityTokenServiceConfig,newRequestMetrics(),awsCredentials.GetCredentials().AccessKey,awsCredentials.GetCredentials().SecretKey);// This is the point, when you have the final set of required Headers.variamSTSRequestHeaders=iamRequest.Headers;// Step 3: Convert the headers into a base64 value needed by Vault.varbase64EncodedIamRequestHeaders=Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(iamSTSRequestHeaders)));// Step 4: Setup the IAM AWS Auth Info.IAuthMethodInfoauthMethod=newIAMAWSAuthMethodInfo(nonce:nonce,roleName:roleName,requestHeaders:base64EncodedIamRequestHeaders);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the aws-iam role// setup the Azure based auth to get the right token.IAuthMethodInfoauthMethod=newAzureAuthMethodInfo(roleName,jwt);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the azure jwt// setup the CloudFoundry based auth to get the right token.IAuthMethodInfoauthMethod=newCloudFoundryAuthMethodInfo(roleName,instanceCertContent,instanceKeyContent);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the CloudFoundry jwt- I have created GH Gist with a helper class to generate on-demand CloudFoundry signature.
- https://gist.github.com/rajanadar/84769efeca64e0128d7a8a627b7bb4db
- Use the
CloudFoundrySignatureProviderclass as follows
varsigning_time=CloudFoundrySignatureProvider.GetFormattedSigningTime(DateTime.UtcNow);varsignature=CloudFoundrySignatureProvider.GetSignature(signingTime,cfInstanceCertContent,roleName,cfInstanceKeyContent);IAuthMethodInfoauthMethod=newGitHubAuthMethodInfo(personalAccessToken);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the github token.// setup the Google Cloud based auth to get the right token.IAuthMethodInfoauthMethod=newGoogleCloudAuthMethodInfo(roleName,jwt);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the Google Cloud jwt// setup the JWT/OIDC based auth to get the right token.IAuthMethodInfoauthMethod=newJWTAuthMethodInfo(roleName,jwt);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the jwt// setup the Kubernetes based auth to get the right token.IAuthMethodInfoauthMethod=newKubernetesAuthMethodInfo(roleName,jwt);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the Kubernetes jwtIAuthMethodInfoauthMethod=newLDAPAuthMethodInfo(userName,password);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the LDAP username and password.- You can use the methods to CRUD LDAP groups and users now.
await_authenticatedVaultClient.V1.Auth.LDAP.WriteGroupAsync(groupName,policies);await_authenticatedVaultClient.V1.Auth.LDAP.ReadGroupAsync(groupName);await_authenticatedVaultClient.V1.Auth.LDAP.ReadAllGroupsAsync();await_authenticatedVaultClient.V1.Auth.LDAP.DeleteGroupAsync(groupName);await_authenticatedVaultClient.V1.Auth.LDAP.WriteUserAsync(username,policies,groups);await_authenticatedVaultClient.V1.Auth.LDAP.ReadUserAsync(username);await_authenticatedVaultClient.V1.Auth.LDAP.ReadAllUsersAsync();await_authenticatedVaultClient.V1.Auth.LDAP.DeleteUserAsync(username);Requires https://github.com/wintoncode/vault-plugin-auth-kerberos .
IAuthMethodInfoauthMethod=newKerberosAuthMethodInfo();// uses network credential by default.// IAuthMethodInfo authMethod = new KerberosAuthMethodInfo(credentials); // use your own ICredentialsvarvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the // vault token/policies mapped to the current ActiveDirectory/Kerberos identity.If you are dealing with a keytab file and krb5 config file and want to use VaultSharp, you can do that using the following two steps:
- Use this gist to generate SP-Nego-Token from the keytab and krb5 file: https://gist.github.com/rajanadar/28c86d967695262bfe1f17ae82fb3d3d
- Once you have the token use VaultSettings.BeforeApiRequestAction to set the Authorization header to the Sp-nego-toekn value from the above helper method.
varrequestHeaders=newDictionary<string,object>{{"date",newList<string>{"Fri, 22 Aug 2019 21:02:19 GMT"}},{"(request-target)",newList<string>{"get /v1/auth/oci/login/devrole"}},{"host",newList<string>{"127.0.0.1"}},{"content-type",newList<string>{"application/json"}},{"authorization",newList<string>{"Signature algorithm=\"rsa-sha256\",headers=\"date (request-target) host\",keyId=\"ocid1.tenancy.oc1..aaaaaaaaba3pv6wkcr4jqae5f15p2b2m2yt2j6rx32uzr4h25vqstifsfdsq/ocid1.user.oc1..aaaaaaaat5nvwcna5j6aqzjcaty5eqbb6qt2jvpkanghtgdaqedqw3rynjq/73:61:a2:21:67:e0:df:be:7e:4b:93:1e:15:98:a5:b7\",signature=\"GBas7grhyrhSKHP6AVIj/h5/Vp8bd/peM79H9Wv8kjoaCivujVXlpbKLjMPeDUhxkFIWtTtLBj3sUzaFj34XE6YZAHc9r2DmE4pMwOAy/kiITcZxa1oHPOeRheC0jP2dqbTll8fmTZVwKZOKHYPtrLJIJQHJjNvxFWeHQjMaR7M=\",version=\"1\""}}};IAuthMethodInfoauthMethod=newOCIAuthMethodInfo(roleName,requestHeaders);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the OCI entity.IAuthMethodInfoauthMethod=newOktaAuthMethodInfo(userName,password);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the Okta username and password.stringnonce="<nonce>";varchallengeResponse=awaitvaultClient.V1.Auth.Okta.VerifyPushChallengeAsync(nonce);varanswer=challengeResponse.Data.CorrectAnswer;// verify this answerIAuthMethodInfoauthMethod=newRADIUSAuthMethodInfo(userName,password);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the RADIUS username and password.// Please note that the certificate needs to be in pkcs12 format with a private key.// Turn your cert + key into pkcs12 format with the following command:// openssl pkcs12 -export -out Cert.p12 -in your-cert.pem -inkey your-key.pemvarcertificate=newX509Certificate2(your-p12-bytes,your-pass);IAuthMethodInfoauthMethod=newCertAuthMethodInfo(certificate);// Optionally, you can also provide a Certificate Role Name during Auth.// IAuthMethodInfo authMethod = new CertAuthMethodInfo(certificate, certificateRoleName);// And if you want to use the full chain of client-certificates, then use this overload// X509Certificate2Collection x509Certificate2Collection = <load the full chain of certs>;// IAuthMethodInfo authMethod = new CertAuthMethodInfo(x509Certificate2Collection);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the client certificate.IAuthMethodInfoauthMethod=newTokenAuthMethodInfo(vaultToken);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the vault token.- You can use the
CreateTokenAsyncmethod to create various types of tokens.
CreateTokenRequestrequest=newCreateTokenRequest();// CreateTokenRequest has options to create orphaned tokens, role based tokens etc. with attached policies.Secret<object>tokenData=await_authenticatedVaultClient.V1.Auth.Token.CreateTokenAsync(request);- You can use the
LookupAsyncmethod to lookup information about any Vault Token.
stringtoken="token-for-which-you-need-info";Secret<ClientTokenInfo>tokenData=await_authenticatedVaultClient.V1.Auth.Token.LookupAsync(token);- You can use the
LookupSelfAsyncmethod to lookup information about your current Vault Token.
Secret<CallingTokenInfo>tokenData=await_authenticatedVaultClient.V1.Auth.Token.LookupSelfAsync();IAuthMethodInfoauthMethod=newUserPassAuthMethodInfo(username,password);varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);// any operations done using the vaultClient will use the// vault token/policies mapped to the username/password.- In cases where the Vault Server has a supported Auth backend, not YET supported by VaultSharp, you can use the CustomAuthMethodInfo
- In this approach, you write the delegate logic that gets the token from Vault along with lease renewal info etc.
Implementing Custom Token Provider
The CustomAuthMethodInfo constructor accepts a delegate that returns an AuthInfo object. This is where you provide your Vault token:
privateTask<AuthInfo>GetCustomAuthMethodInfo(){varvaultOptions=newVaultOptions();returnTask.FromResult(newAuthInfo(){ClientToken=vaultOptions.VaultToken});}Creating the Vault Client with Custom Auth
Once you have your token provider, you can initialize the VaultClient using CustomAuthMethodInfo.
privateVaultClientBuildVaultClient(){varvaultSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",newCustomAuthMethodInfo("vault-server-auth-method",GetCustomAuthMethodInfo));returnnewVaultClient(vaultSettings);}// Once VaultSharp evaluates the delegate, VaultSharp can now provide you with the associated lease info for the Token as well.// authMethod.ReturnedLoginAuthInfo has all the info including the token and renewal info.Adding Retry Logic for Custom Auth Method
With the custom auth method, there is an easy way to write in your own retry logic:
publicasyncTask<Secret<T>>ReadSecretAsync<T>(stringpath,stringmountPoint=null,stringwrapTimeToLive=null){try{returnawait_vaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync<T>(path,mountPoint,wrapTimeToLive);}catch(VaultApiExceptionex)when(ex.HttpStatusCode==HttpStatusCode.Forbidden){_logger?.LogError(ex,"Vault Could not be authenticated with current token retrieving new token and trying again.");_vaultClient.V1.Auth.ResetVaultToken();returnawait_vaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync<T>(path,mountPoint,wrapTimeToLive);}}- Please note that the app-id auth backend has been deprecated by Vault. They recommend us to use the AppRole backend.
- So VaultSharp doesn't support App Id natively.
- If you are in dire need of the App Id support, please raise an issue.
- Please note that this legacy Auth Method is not supported by Vault anymore.
- Instead Vault Enterprise contains a fully-supported MFA system.
- It is significantly more complete and flexible and which can be used throughout Vault's API.
- Please see the System Backend section of the docs for the Enterprise MFA apis.
- Whenever you initialize VaultSharp with an appropriate AuthMethod, VaultSharp fetches the vault token on the first authenticated Vault operation requested by the host app.
- Once VaultSharp has this token, it never re-fetches the token.
- This means, when the token expires, Vault calls will start failing.
- The older way to solve for this is for the host app to keep track of the token's TTL and re-initialize VaultClient. This ensures that VaultSharp will fetch the vault-token again.
- However, a lot of our clients don't want to mess with the singleton nature of VaultClient.
- So VaultSharp now supports the ability to set a flag that tells VaultSharp to refetch the vault token during the next Vault operation.
- As a client, whenever you determine that the token needs to be re-fetched, call this method.
- It'll make VaultSharp fetch the vault token again before the next operation.
// when it is time to re-fetch the login token, just set this flag.vaultClient.V1.Auth.ResetVaultToken();- VaultSharp supports all secrets engines supported by the Vault Service
- Here is a sample to instantiate the vault client with each of the secrets engine
All of the below examples assume that you have a vault client instance ready. e.g.
// Initialize one of the several auth methods.IAuthMethodInfoauthMethod=newTokenAuthMethodInfo("MY_VAULT_TOKEN");// Initialize settings. You can also set proxies, custom delegates etc. here.varvaultClientSettings=newVaultClientSettings("https://MY_VAULT_SERVER:8200",authMethod);IVaultClientvaultClient=newVaultClient(vaultClientSettings);- This method offers the credential information for a given role.
Secret<ActiveDirectoryCredentials>adCreds=awaitvaultClient.V1.Secrets.ActiveDirectory.GetCredentialsAsync(role);stringcurrentPassword=adCreds.Data.CurrentPassword;- This endpoint generates dynamic RAM credentials based on the named role.
Secret<AliCloudCredentials>aliCloudCreds=awaitvaultClient.V1.Secrets.AliCloud.GetCredentialsAsync(role);stringaccessKey=aliCloudCreds.Data.AccessKey;stringsecretKey=aliCloudCreds.Data.SecretKey;stringsecurityToken=aliCloudCreds.Data.SecurityToken;stringexpiration=aliCloudCreds.Data.Expiration;- This endpoint configures the root IAM credentials to communicate with AWS.
varconfigureRootIAMCredentialsModel=newConfigureRootIAMCredentialsModel{AccessKey="<>",SecretKey="<>",Region="<>"};awaitvaultClient.V1.Secrets.AWS.ConfigureRootIAMCredentialsAsync(configureRootIAMCredentialsModel);- This endpoint allows you to read non-secure values that have been configured in the config/root endpoint.
- In particular, the secret_key parameter is never returned.
Secret<RootIAMCredentialsConfigModel>config=awaitvaultClient.V1.Secrets.AWS.GetRootIAMCredentialsConfigAsync();- When you have configured Vault with static credentials, you can use this endpoint to have Vault rotate the access key it used.
Secret<RotateRootIAMCredentialsResponseModel>response=awaitvaultClient.V1.Secrets.AWS.RotateRootIAMCredentialsAsync();stringnewAccessKey=response.Data.NewAccessKey;- This endpoint configures lease settings for the AWS secrets engine.
varleaseConfigModel=newAWSLeaseConfigModel{Lease="36h",MaximumLease="72h"};awaitvaultClient.V1.Secrets.AWS.ConfigureLeaseAsync(leaseConfigModel);- This endpoint returns the current lease settings for the AWS secrets engine.
Secret<AWSLeaseConfigModel>lease=awaitvaultClient.V1.Secrets.AWS.GetLeaseConfigAsync();- This endpoint creates or updates the role with the given name.
varrole=newCreateAWSRoleModel{CredentialType=AWSCredentialsType.federation_token,PolicyDocument="{\"Version\": \"...\"}"};awaitvaultClient.V1.Secrets.AWS.WriteRoleAsync("my-role-name",role);- This endpoint reads details of one AWS Role.
Secret<AWSRoleModel>role=awaitvaultClient.V1.Secrets.AWS.ReadRoleAsync(roleName);List<AWSCredentialsType>credTypes=role.Data.CredentialTypes;- This endpoint reads all the AWS Roles
Secret<ListInfo>roles=awaitvaultClient.V1.Secrets.AWS.ReadAllRolesAsync();List<string>names=roles.Data;- This endpoint generates dynamic IAM credentials based on the named role.
Secret<AWSCredentials>awsCreds=awaitvaultClient.V1.Secrets.AWS.GetCredentialsAsync(role);stringaccessKey=awsCreds.Data.AccessKey;stringsecretKey=awsCreds.Data.SecretKey;stringsecurityToken=awsCreds.Data.SecurityToken;- This generates a dynamic IAM credential with an STS token based on the named role.
Secret<AWSCredentials>awsCreds=awaitvaultClient.V1.Secrets.AWS.GenerateSTSCredentialsAsync(role,ttl);stringaccessKey=awsCreds.Data.AccessKey;stringsecretKey=awsCreds.Data.SecretKey;stringsecurityToken=awsCreds.Data.SecurityToken;- This endpoint generates a new service principal based on the named role.
Secret<AzureCredentials>azureCredentials=awaitvaultClient.V1.Secrets.Azure.GetCredentialsAsync(roleName);stringclientId=azureCredentials.Data.ClientId;stringclientSecret=azureCredentials.Data.ClientSecret;- This endpoint generates a dynamic Consul token based on the given role definition.
// Generate a dynamic Consul credentialSecret<ConsulCredentials>consulCreds=awaitvaultClient.V1.Secrets.Consul.GetCredentialsAsync(consulRole);stringconsulToken=consulCredentials.Data.Token;- This endpoint retrieves the secret at the specified location.
Secret<Dictionary<string,object>>secret=awaitvaultClient.V1.Secrets.Cubbyhole.ReadSecretAsync(secretPath);Dictionary<string,object>secretValues=secret.Data;- This endpoint returns a list of secret entries at the specified location.
- Folders are suffixed with /. The input must be a folder; list on a file will not return a value.
- The values themselves are not accessible via this command.
Secret<ListInfo>secret=awaitvaultClient.V1.Secrets.Cubbyhole.ReadSecretPathsAsync(folderPath);ListInfopaths=secret.Data;- This endpoint stores a secret at the specified location.
varvalue=newDictionary<string,object>{{"key1","val1"},{"key2",2}};awaitvaultClient.V1.Secrets.Cubbyhole.WriteSecretAsync(secretPath,value);- This endpoint deletes the secret at the specified location.
awaitvaultClient.V1.Secrets.Cubbyhole.DeleteSecretAsync(secretPath);- This endpoint generates a new set of dynamic credentials based on the named role.
Secret<UsernamePasswordCredentials>dbCreds=awaitvaultClient.V1.Secrets.Database.GetCredentialsAsync(role);stringusername=dbCreds.Data.Username;stringpassword=dbCreds.Data.Password;- These endpoints manage the creation, reading and deletion of DB roles.
awaitvaultClient.V1.Secrets.Database.CreateRoleAsync(roleName,roleRequest);awaitvaultClient.V1.Secrets.Database.ReadRoleAsync(roleName);awaitvaultClient.V1.Secrets.Database.ReadAllRolesAsync();awaitvaultClient.V1.Secrets.Database.DeleteRoleAsync(roleName);- These endpoints manage the creation, reading and deletion of static DB roles.
awaitvaultClient.V1.Secrets.Database.CreateStaticRoleAsync(roleName,roleRequest);awaitvaultClient.V1.Secrets.Database.ReadStaticRoleAsync(roleName);awaitvaultClient.V1.Secrets.Database.ReadAllStaticRolesAsync();awaitvaultClient.V1.Secrets.Database.DeleteStaticRoleAsync(roleName);- This endpoint generates a new set of static credentials based on the named role.
Secret<StaticCredentials>dbCreds=awaitvaultClient.V1.Secrets.Database.GetStaticCredentialsAsync(role);- This endpoint rotates the static credentials on demand.
awaitvaultClient.V1.Secrets.Database.RotateStaticCredentialsAsync(role);- Generates an OAuth2 token with the scopes defined on the roleset. This OAuth access token can be used in GCP API calls
Secret<GoogleCloudOAuth2Token>oauthSecret=awaitvaultClient.V1.Secrets.GoogleCloud.GetOAuth2TokenAsync(roleset);stringtoken=oauthSecret.Data.Token;- Generates a service account key.
Secret<GoogleCloudServiceAccountKey>privateKeySecret=awaitvaultClient.V1.Secrets.GoogleCloud.GenerateServiceAccountKeyAsync(roleset,keyAlgorithm,privateKeyType);stringprivateKeyData=privateKeySecret.Data.Base64EncodedPrivateKeyData;awaitvaultClient.V1.Secrets.GoogleCloudKMS.EncryptAsync(keyName,requestOptions);awaitvaultClient.V1.Secrets.GoogleCloudKMS.DecryptAsync(keyName,requestOptions);awaitvaultClient.V1.Secrets.GoogleCloudKMS.ReEncryptAsync(keyName,requestOptions);awaitvaultClient.V1.Secrets.GoogleCloudKMS.SignAsync(keyName,requestOptions);awaitvaultClient.V1.Secrets.GoogleCloudKMS.VerifyAsync(keyName,requestOptions);- VaultSharp supports both v1 and v2 of the Key Value Secrets Engine.
- Here are examples for both.
- This endpoint stores a secret at the specified location.
- If the value does not yet exist, the calling token must have an ACL policy granting the create capability.
- If the value already exists, the calling token must have an ACL policy granting the update capability.
varvalue=newDictionary<string,object>{{"key1","val1"},{"key2",2}};varwrittenValue=awaitvaultClient.V1.Secrets.KeyValue.V1.WriteSecretAsync(secretPath,value);- Reads the secret at the specified location returning data.
// Use client to read a v1 key-value secret.Secret<Dictionary<string,object>>kv1Secret=awaitvaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync("v1-secret-name");Dictionary<string,object>dataDictionary=kv1Secret.Data;- This endpoint returns a list of key names at the specified location.
- Folders are suffixed with /. The input must be a folder; list on a file will not return a value.
- Note that no policy-based filtering is performed on keys; do not encode sensitive information in key names.
- The values themselves are not accessible via this command.
Secret<ListInfo>secret=awaitvaultClient.V1.Secrets.KeyValue.V1.ReadSecretPathsAsync(path);ListInfopaths=secret.Data;- This endpoint deletes the secret at the specified location.
awaitvaultClient.V1.Secrets.KeyValue.V1.DeleteSecretAsync(secretPath);- This endpoint stores a secret at the specified location.
- If the value does not yet exist, the calling token must have an ACL policy granting the create capability.
- If the value already exists, the calling token must have an ACL policy granting the update capability.
varvalue=newDictionary<string,object>{{"key1","val1"},{"key2",2}};varwrittenValue=awaitvaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(secretPath,value,checkAndSet);- You can also patch a secret that already exists.
- Patching means, replacing/adding new key-values to an existing map of secrets.
varvalueToBeCombined=newDictionary<string,object>{{"key2","new-val2"},{"key3","val3"}};varpatchSecretDataRequest=newPatchSecretDataRequest(){Data=valueToBeCombined};varmetadata=awaitvaultClient.V1.Secrets.KeyValue.V2.PatchSecretAsync(secretPath,valueToBeCombined);- Reads the secret at the specified location returning data and metadata.
// Use client to read a v2 key-value secret.// Very important to provide mountpath and secret name as two separate parameters. Don't provide a single combined string.// Please use named parameters for 100% clarity of code. (the method also takes version and wrapTimeToLive as params)Secret<Dictionary<string,object>>kv2Secret=awaitvaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path:"v2-secret-name",mountPoint:"mountPointIfNotDefault");Dictionary<string,object>dataDictionary=kv2Secret.Data;- Creates or updates the metadata of a secret at the specified location in the K/V v2 secrets engine.
var writeCustomMetadataRequest = new CustomMetadataRequest
{
CustomMetadata = new Dictionary<string, string>
{
{ "owner", "system"},
{ "expired_in", "20331010"}
}
};
await _authenticatedVaultClient.V1.Secrets.KeyValue.V2.WriteSecretMetadataAsync(path, writeCustomMetadataRequest, mountPoint: kv2SecretsEngine.Path);
- Patch the metadata of a secret at specified location in the K/V v2 secrets engine.
var patchCustomMetadataRequest = new CustomMetadataRequest
{
CustomMetadata = new Dictionary<string, string>
{
{ "locale", "EN"},
{ "expired_in", "20341010"}
}
};
await _authenticatedVaultClient.V1.Secrets.KeyValue.V2.PatchSecretMetadataAsync(path, patchCustomMetadataRequest, mountPoint: kv2SecretsEngine.Path)
- Reads the secret metadata at the specified location returning.
Secret<FullSecretMetadata>kv2SecretMetadata=awaitvaultClient.V1.Secrets.KeyValue.V2.ReadSecretMetadataAsync("v1-secret-name");- This endpoint returns a list of key names at the specified location.
- Folders are suffixed with /. The input must be a folder; list on a file will not return a value.
- Note that no policy-based filtering is performed on keys; do not encode sensitive information in key names.
- The values themselves are not accessible via this command.
Secret<ListInfo>secret=awaitvaultClient.V1.Secrets.KeyValue.V2.ReadSecretPathsAsync(path);ListInfopaths=secret.Data;- This endpoint provides the subkeys within a secret entry that exists at the requested path.
- The secret entry at this path will be retrieved and stripped of all data by replacing underlying values of leaf keys (i.e. non-map keys or map keys with no underlying subkeys) with null.
Secret<SecretSubkeysInfo>secret=awaitvaultClient.V1.Secrets.KeyValue.V2.ReadSecretSubkeysAsync(path)
SecretSubkeysInfo subkeys = secret.Data;- This endpoint issues a soft delete of the secret's latest version at the specified location.
- This marks the version as deleted and will stop it from being returned from reads, but the underlying data will not be removed.
- A delete can be undone using the undelete method.
awaitvaultClient.V1.Secrets.KeyValue.V2.DeleteSecretAsync(secretPath);- This endpoint issues a soft delete of the specified versions of the secret.
- This marks the versions as deleted and will stop them from being returned from reads, but the underlying data will not be removed.
- A delete can be undone using the undelete method.
awaitvaultClient.V1.Secrets.KeyValue.V2.DeleteSecretVersionsAsync(secretPath,versions);- Undeletes the data for the provided version and path in the key-value store.
- This restores the data, allowing it to be returned on get requests.
awaitvaultClient.V1.Secrets.KeyValue.V2.UndeleteSecretVersionsAsync(secretPath,versions);- This endpoint destroys the secret at the specified location for the given versions.
awaitvaultClient.V1.Secrets.KeyValue.V2.DestroySecretAsync(secretPath,newList<int>{1,2});- This endpoint permanently deletes the key metadata and all version data for the specified key.
- All version history will be removed.
awaitvaultClient.V1.Secrets.KeyValue.V2.DeleteMetadataAsync(secretPath);- Use this endpoint to generate a signed ID (OIDC) token.
Secret<IdentityToken>token=awaitvaultClient.V1.Secrets.Identity.GetTokenAsync(roleName);stringclientId=token.Data.ClientId;stringtoken=token.Data.Token;- This endpoint can verify the authenticity and active state of a signed ID token.
Secret<bool>activeResponse=awaitvaultClient.V1.Secrets.Identity.IntrospectTokenAsync(token,clientId);boolactive=activeResponse.Data;- Returns information about a named key.
- The keys object will hold information regarding each key version.
- Different information will be returned depending on the key type.
- For example, an asymmetric key will return its public key in a standard format for the type.
Secret<KeyManagementKey>keyManagementKey=awaitvaultClient.V1.Secrets.Enterprise.KeyManagement.ReadKeyAsync(keyName);varkeys=keyManagementKey.Data.Keys;- Returns information about a named key in KMS.
Secret<KeyManagementKMSKey>keyManagementKMSKey=awaitvaultClient.V1.Secrets.Enterprise.KeyManagement.ReadKeyInKMSAsync(kmsName,keyName);varname=keyManagementKMSKey.Data.Name;varpurpose=keyManagementKMSKey.Data.Purpose;varprotection=keyManagementKMSKey.Data.Protection;- Create a new client certificate tied to the given role and scope.
Secret<KMIPCredentials>kmipCredentials=awaitvaultClient.V1.Secrets.Enterprise.KMIP.GetCredentialsAsync(scopeName,roleName);stringcertificateContent=kmipCredentials.Data.CertificateContent;stringprivateKeyContent=kmipCredentials.Data.PrivateKeyContent;Secret<KubernetesCredentials>kubernetesCredentials=awaitvaultClient.V1.Secrets.Kubernetes.GetCredentialsAsync(ksRoleName,ksNamespace);stringserviceAccountToken=kubernetesCredentials.Data.ServiceAccountToken;- Generates a dynamic MongoDBAtlas creds based on the given role definition.
Secret<MongoDBAtlasCredentials>creds=awaitvaultClient.V1.Secrets.MongoDBAtlas.GetCredentialsAsync(name);stringprivateKey=creds.Data.PrivateKey;stringpublicKey=creds.Data.PublicKey;- Generates a dynamic Nomad token based on the given role definition.
Secret<NomadCredentials>nomadCredentials=awaitvaultClient.V1.Secrets.Nomad.GetCredentialsAsync(roleName);stringaccessorId=nomadCredentials.Data.AccessorId;stringsecretId=nomadCredentials.Data.SecretId;- This endpoint offers the credential information for a given role.
Secret<LDAPCredentials>credentials=awaitvaultClient.V1.Secrets.OpenLDAP.GetDynamicCredentialsAsync(roleName);stringusername=credentials.Data.Username;stringpassword=credentials.Data.Password;- This endpoint offers the credential information for a given static-role.
Secret<StaticCredentials>credentials=awaitvaultClient.V1.Secrets.OpenLDAP.GetStaticCredentialsAsync(roleName);stringusername=credentials.Data.Username;stringpassword=credentials.Data.Password;varcertificateCredentialsRequestOptions=newCertificateCredentialsRequestOptions{// initialize };Secret<CertificateCredentials>certSecret=awaitvaultClient.V1.Secrets.PKI.GetCredentialsAsync(pkiRoleName,certificateCredentialsRequestOptions);stringprivateKeyContent=certSecret.Data.PrivateKeyContent;varsignCertificateRequestOptions=newSignCertificateRequestOptions{// initialize };Secret<SignedCertificateData>certSecret=awaitvaultClient.V1.Secrets.PKI.SignCertificateAsync(pkiRoleName,signCertificateRequestOptions);stringcertificateContent=certSecret.Data.CertificateContent;Secret<RevokeCertificateResponse>revoke=awaitvaultClient.V1.Secrets.PKI.RevokeCertificateAsync(serialNumber);longrevocationTime=revoke.Data.RevocationTime;varrequest=newCertificateTidyRequest{TidyCertStore=false,TidyRevokedCerts=true};awaitvaultClient.V1.Secrets.PKI.TidyAsync(request);varrequest=newCertificateAutoTidyRequest{TidyCertStore=false,TidyRevokedCerts=true};awaitvaultClient.V1.Secrets.PKI.AutoTidyAsync(request);vartidyStatus=awaitvaultClient.V1.Secrets.PKI.GetTidyStatusAsync();CertificateTidyStatestate=tidyStatus.Data.TidyState;vartidyStatus=awaitvaultClient.V1.Secrets.PKI.CancelTidyAsync();CertificateTidyStatestate=tidyStatus.Data.TidyState;- This endpoint retrieves a list of certificate keys (serial numbers)
varkeys=awaitvaultClient.V1.Secrets.PKI.ListCertificatesAsync(mountpoint);Assert.IsTrue(keys.Any(k =>k=="17:67:16:b0:b9:45:58:c0:3a:29:e3:cb:d6:98:33:7a:a6:3b:66:c1"));- This endpoint retrieves a list of revoked certificate keys (serial numbers)
varkeys=awaitvaultClient.V1.Secrets.PKI.ListRevokedCertificatesAsync(mountpoint);Assert.IsTrue(keys.Any(k =>k=="17:67:16:b0:b9:45:58:c0:3a:29:e3:cb:d6:98:33:7a:a6:3b:66:c1"));- This endpoint retrieves a certificate by key (serial number)
- The certificate format is always PEM.
- This is an unauthenticated endpoint.
varcert=awaitvaultClient.V1.Secrets.PKI.ReadCertificateAsync("17:67:16:b0:b9:45:58:c0:3a:29:e3:cb:d6:98:33:7a:a6:3b:66:c1",mountpoint);Assert.NotNull(cert.CertificateContent);- This endpoint retrieves the CA certificate in raw DER-encoded form.
- The CA certificate can be returned in PEM or DER format.
- This is an unauthenticated endpoint.
varcaCert=awaitvaultClient.V1.Secrets.PKI.ReadCACertificateAsync(CertificateFormat.pem,mountpoint);Assert.NotNull(caCert.CertificateContent);varissuers=awaitvaultClient.V1.Secrets.PKI.Issuers.ListIssuers();List<string>issuerKeys=issuers.Data.Keys;varissuerData=newIssuerData{CommonName="example.com",KeyType=PrivateKeyType.rsa,KeyBits=4096};Secret<IssuerResponseData>issuer=awaitvaultClient.V1.Secrets.PKI.Issuers.AddIssuer(issuerData);stringissuerId=issuer.Data.IssuerId;Secret<IssuerConfigResponseData>config=awaitvaultClient.V1.Secrets.PKI.Issuers.GetIssuerConfigData("my-issuer");stringissuerName=config.Data.IssuerName;varconfigData=newIssuerConfigRequestData{IssuerName="my-issuer",Usage="issuing-certificates,crl-signing"};Secret<IssuerConfigResponseData>config=awaitvaultClient.V1.Secrets.PKI.Issuers.ConfigureIssuer(configData);stringissuerId=config.Data.IssuerId;awaitvaultClient.V1.Secrets.PKI.Issuers.DeleteIssuer("my-issuer");varkeys=awaitvaultClient.V1.Secrets.PKI.Keys.ListKeys();List<string>keyIds=keys.Data.Keys;varkeyData=newKeyData{KeyType=PrivateKeyType.rsa,KeyBits=4096,KeyName="my-key"};Secret<KeyData>key=awaitvaultClient.V1.Secrets.PKI.Keys.GenerateKey(keyData);stringkeyName=key.Data.KeyName;Secret<KeyData>key=awaitvaultClient.V1.Secrets.PKI.Keys.GetKey("my-key");PrivateKeyTypekeyType=key.Data.KeyType;varimportData=newImportKeyData{KeyName="my-key",PemBundle="-----BEGIN RSA PRIVATE KEY-----\n..."};Secret<ImportKeyData>key=awaitvaultClient.V1.Secrets.PKI.Keys.ImportKey(importData);stringkeyName=key.Data.KeyName;awaitvaultClient.V1.Secrets.PKI.Keys.DeleteKey("my-key");varroles=awaitvaultClient.V1.Secrets.PKI.Roles.ListRoles();List<string>roleKeys=roles.Data.Keys;varroleData=newRoleData{Name="my-role",AllowedDomains=newList<string>{"example.com"},AllowSubdomains=true};Secret<RoleData>role=awaitvaultClient.V1.Secrets.PKI.Roles.AddRole(roleData);PrivateKeyRoleTypekeyType=role.Data.KeyType;Secret<RoleData>role=awaitvaultClient.V1.Secrets.PKI.Roles.GetRole("my-role");boolallowAnyName=role.Data.AllowAnyName;awaitvaultClient.V1.Secrets.PKI.Roles.DeleteRole("my-role");- This endpoint generates a new set of dynamic credentials based on the named role.
Secret<UsernamePasswordCredentials>secret=awaitvaultClient.V1.Secrets.RabbitMQ.GetCredentialsAsync(roleName);stringusername=secret.Data.Username;stringpassword=secret.Data.Password;- These endpoints manage the creation, reading and deletion of RabbitMQ roles.
varvirtualHostName="/";varvirtualHostPermission=new{write=".*",read=".*"};varvirtualHosts=newDictionary<string,object>(){{virtualHostName,virtualHostPermission}};varvirtualHostsJson=JsonSerializer.Serialize(virtualHosts);varrole=newRabbitMQRole(){VHosts=virtualHostsJson} await vaultClient.V1.Secrets.RabbitMQ.CreateRoleAsync(roleName,role,mountPoint);awaitvaultClient.V1.Secrets.RabbitMQ.ReadRoleAsync(roleName,mountPoint);awaitvaultClient.V1.Secrets.RabbitMQ.DeleteRoleAsync(roleName,mountPoint);- This endpoint creates credentials for a specific username and IP with the parameters defined in the given role.
Secret<SSHCredentials>sshCreds=awaitvaultClient.V1.Secrets.SSH.GetCredentialsAsync(role,ipAddress,username);stringsshKey=sshCreds.Data.Key;- This endpoint signs an SSH public key based on the supplied parameters, subject to the restrictions contained in the role named in the endpoint.
SignKeyRequestrequest=newSignKeyRequest{PublicKey="ipsem"};Secret<SignedKeyResponse>signedKey=awaitvaultClient.V1.Secrets.SSH.SignKeyAsync(roleName,request);stringsignedKey=signedKey.Data.SignedKey;- This endpoint returns a Terraform Cloud token based on the given role definition.
- For Organization and Team roles, the same API token is returned until the token is rotated with rotate-role.
- For User roles, a new token is generated with each request.
Secret<TerraformCredentials>secret=awaitvaultClient.V1.Secrets.Terraform.GetCredentialsAsync(role);stringtoken=secret.Data.Token;stringtokenId=secret.Data.TokenId;This endpoint generates a new time-based one-time use password based on the named key.
Secret<TOTPCode>totpSecret=awaitvaultClient.V1.Secrets.TOTP.GetCodeAsync(keyName);stringcode=totpSecret.Data.Code;This endpoint validates a time-based one-time use password generated from the named key.
Secret<TOTPCodeValidity>totpValidity=awaitvaultClient.V1.Secrets.TOTP.ValidateCodeAsync(keyName,code);boolvalid=totpValidity.Data.Valid;This endpoint creates or updates a key definition. You can create both Vault based or non-vault based keys.
TOTPCreateKeyRequestrequest=newTOTPCreateKeyRequest{Issuer="Google",AccountName="scooby@gmail.com",KeyGenerationOption=newTOTPVaultBasedKeyGeneration{// specific stuff }// for non-vault based, use new TOTPNonVaultBasedKeyGeneration { // specific stuff }};Secret<TOTPCreateKeyResponse>response=awaitvaultClient.V1.Secrets.TOTP.CreateKeyAsync(keyName,request);varbarcode=response.Data.Barcode;This endpoint queries the key definition.
Secret<TOTPKey>key=awaitvaultClient.V1.Secrets.TOTP.ReadKeyAsync(keyName);This endpoint returns a list of available keys. Only the key names are returned, not any values.
Secret<ListInfo>keys=awaitvaultClient.V1.Secrets.TOTP.ReadAllKeysAsync();This endpoint deletes the key definition.
awaitvaultClient.V1.Secrets.TOTP.DeleteKeyAsync(keyName);varencodeOptions=newEncodeRequestOptions{Value="ipsem"};Secret<EncodedResponse>response=await_authenticatedVaultClient.V1.Secrets.Enterprise.Transform.EncodeAsync(roleName,encodeOptions);response.Data.EncodedValue;varencodeOptions=newEncodeRequestOptions{BatchItems=newList<EncodingItem>{newEncodingItem{Value="ipsem1"},newEncodingItem{Value="ipsem2"}}};Secret<EncodedResponse>response=await_authenticatedVaultClient.V1.Secrets.Enterprise.Transform.EncodeAsync(roleName,encodeOptions);response.Data.EncodedItems;vardecodeOptions=newDecodeRequestOptions{Value="ipsem"};Secret<DecodedResponse>response=await_authenticatedVaultClient.V1.Secrets.Enterprise.Transform.DecodeAsync(roleName,decodeOptions);response.Data.DecodedValue;vardecodeOptions=newDecodeRequestOptions{BatchItems=newList<DecodingItem>{newDecodingItem{Value="ipsem1"},newDecodingItem{Value="ipsem2"}}};Secret<DecodedResponse>response=await_authenticatedVaultClient.V1.Secrets.Enterprise.Transform.DecodeAsync(roleName,decodeOptions);response.Data.DecodedItems;varkeyName="test_key";varcontext="context1";varplainText="raja";varencodedPlainText=Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));varencodedContext=Convert.ToBase64String(Encoding.UTF8.GetBytes(context));varencryptOptions=newEncryptRequestOptions{Base64EncodedPlainText=encodedPlainText,Base64EncodedContext=encodedContext,};Secret<EncryptionResponse>encryptionResponse=await_authenticatedVaultClient.V1.Secrets.Transit.EncryptAsync(keyName,encryptOptions);stringcipherText=encryptionResponse.Data.CipherText;varencryptOptions=newEncryptRequestOptions{BatchedEncryptionItems=newList<EncryptionItem>{newEncryptionItem{Base64EncodedContext=encodedContext1,Base64EncodedPlainText=encodedPlainText1},newEncryptionItem{Base64EncodedContext=encodedContext2,Base64EncodedPlainText=encodedPlainText2},newEncryptionItem{Base64EncodedContext=encodedContext3,Base64EncodedPlainText=encodedPlainText3},}};Secret<EncryptionResponse>encryptionResponse=await_authenticatedVaultClient.V1.Secrets.Transit.EncryptAsync(keyName,encryptOptions);stringfirstCipherText=encryptionResponse.Data.BatchedResults.First().CipherText;vardecryptOptions=newDecryptRequestOptions{CipherText=cipherText,Base64EncodedContext=encodedContext,};Secret<DecryptionResponse>decryptionResponse=await_authenticatedVaultClient.V1.Secrets.Transit.DecryptAsync(keyName,decryptOptions);stringencodedPlainText=decryptionResponse.Data.Base64EncodedPlainText;vardecryptOptions=newDecryptRequestOptions{BatchedDecryptionItems=newList<DecryptionItem>{newDecryptionItem{Base64EncodedContext=encodedContext1,CipherText=cipherText1},newDecryptionItem{Base64EncodedContext=encodedContext2,CipherText=cipherText2},newDecryptionItem{Base64EncodedContext=encodedContext3,CipherText=cipherText3},}};Secret<DecryptionResponse>decryptionResponse=await_authenticatedVaultClient.V1.Secrets.Transit.DecryptAsync(keyName,decryptOptions);stringfirstEncodedPlainText=decryptionResponse.Data.BatchedResults.First().Base64EncodedPlainText;// Generate Data KeyvardataKeyOptions=newDataKeyRequestOptions{Base64EncodedContext=encodedContext,Nonce=nonce};Secret<DataKeyResponse>dataKeyResponse=await_authenticatedVaultClient.V1.Secrets.Transit.GenerateDataKeyAsync(keyType,keyName,dataKeyOptions);varencodedDataKeyPlainText=dataKeyResponse.Data.Base64EncodedPlainText;vardataKeyCipherText=dataKeyResponse.Data.Base64EncodedCipherText;varallKeys=await_authenticatedVaultClient.V1.Secrets.Transit.ReadAllEncryptionKeysAsync();vartrimOptions=newTrimKeyRequestOptions{MinimumAvailableVersion=2};await_authenticatedVaultClient.V1.Secrets.Transit.TrimKeyAsync(keyName,trimOptions);stringversion="latest";Secret<ExportedKeyInfo>exportedKeyInfo=await_authenticatedVaultClient.V1.Secrets.Transit.ExportKeyAsync(TransitKeyCategory.encryption_key,keyName,version);- In order for this call to work, the key must have been created with allow_plaintext_backup set to true.
varbackup=await_authenticatedVaultClient.V1.Secrets.Transit.BackupKeyAsync(keyName);stringbackupData=backup.Data.BackupData;varrestoreData=newRestoreKeyRequestOptions{BackupData=previouslyBackedUpData,Force=true};await_authenticatedVaultClient.V1.Secrets.Transit.RestoreKeyAsync(keyName,restoreData);varbyteCountRequested=64;varrandomOpts=newRandomBytesRequestOptions{Format=OutputEncodingFormat.base64};varbase64Response=await_authenticatedVaultClient.V1.Secrets.Transit.GenerateRandomBytesAsync(byteCountRequested,randomOpts);varbase64EncodedRandomData=base64Response.Data.EncodedRandomBytes;varhashOpts=newHashRequestOptions{Format=OutputEncodingFormat.base64,Base64EncodedInput=encodedStringToHash};varhashResponse=await_authenticatedVaultClient.V1.Secrets.Transit.HashDataAsync(HashAlgorithm.sha2_256,hashOpts);varhashString=hashResponse.Data.HashSum;varhmacOptions=newHmacRequestOptions{Base64EncodedInput=encodedPlainText};varhmacResponse=await_authenticatedVaultClient.V1.Secrets.Transit.GenerateHmacAsync(HashAlgorithm.sha2_256,keyName,hmacOptions);varhmacList=newHmacRequestOptions{BatchInput=newList<HmacSingleInput>{newHmacSingleInput{Base64EncodedInput=encodedText},newHmacSingleInput{Base64EncodedInput=encodedText2},newHmacSingleInput{Base64EncodedInput=encodedText3}}};varhmacResponse=await_authenticatedVaultClient.V1.Secrets.Transit.GenerateHmacAsync(HashAlgorithm.sha2_256,keyName,hmacList);varsignOptions=newSignRequestOptions{Base64EncodedInput=encodedText,SignatureAlgorithm=SignatureAlgorithm.Pkcs1v15,MarshalingAlgorithm=MarshalingAlgorithm.Asn1};varsignResponse=await_authenticatedVaultClient.V1.Secrets.Transit.SignDataAsync(HashAlgorithm.sha2_256,keyName,signOptions);varsignList=newSignRequestOptions{BatchInput=newList<SignSingleInput>{newSignSingleInput{Base64EncodedInput=encodedText},newSignSingleInput{Base64EncodedInput=encodedText2},newSignSingleInput{Base64EncodedInput=encodedText3}},SignatureAlgorithm=SignatureAlgorithm.Pkcs1v15,MarshalingAlgorithm=MarshalingAlgorithm.Asn1};varsignResponse=await_authenticatedVaultClient.V1.Secrets.Transit.SignDataAsync(HashAlgorithm.sha2_256,keyName,signList);varverifyOptions=newVerifyRequestOptions{Base64EncodedInput=base64Input,Hmac=hmacToVerify,MarshalingAlgorithm=MarshalingAlgorithm.Asn1};varverifyResponse=await_authenticatedVaultClient.V1.Secrets.Transit.VerifySignedDataAsync(HashAlgorithm.sha2_256,keyName,verifyOptions);varisValid=verifyResponse.Data.Valid;varverifyOptions=newVerifyRequestOptions{Base64EncodedInput=base64Input,Signature=signResponse.Data.Signature,SignatureAlgorithm=SignatureAlgorithm.Pkcs1v15,MarshalingAlgorithm=MarshalingAlgorithm.Asn1};varverifyResponse=await_authenticatedVaultClient.V1.Secrets.Transit.VerifySignedDataAsync(HashAlgorithm.sha2_256,keyname,verifyOptions);varisValid=verifyResponse.Data.Valid;varcacheResult=await_authenticatedVaultClient.V1.Secrets.Transit.ReadCacheConfigAsync();varcacheSize=cacheResult.Data.Size;- Configuration changes will not be applied until the transit plugin is reloaded which can be achieved using the
/sys/plugins/reload/backendendpoint.
varcacheOptions=newCacheConfigRequestOptions{Size=cacheResult.Data.Size+1};awaittransit.SetCacheConfigAsync(cacheOptions);- The system backend is a default backend in Vault that is mounted at the /sys endpoint.
- This endpoint cannot be disabled or moved, and is used to configure Vault and interact with many of Vault's internal features.
VaultSharp already supports several of the System backend features.
vaultClient.V1.System.<method>// The method you are looking for.- Yes you can.
- The
VaultClientSettingsobject takes aMyHttpClientProviderFuncdelegate that can be as follows. - Don't worry about setting any vault specific URL, timeout etc. on this http client. VaultSharp will do that.
varsettings=newVaultClientSettings("http://localhost:8200",authMethodInfo){Namespace="mynamespace",MyHttpClientProviderFunc= handler =>newHttpClient(handler)};- This library is written for Hashicorp's Vault Service
- The Vault service is evolving constantly and the Hashicorp team is rapidly working on it.
- Because this client library is intended to facilititate the Vault Service operations, this library makes it easier for its consumers to relate to the Vault service it supports.
- Hence a version of 0.11.x denotes that this library will support the Vault 0.11.x Service Apis.
- Tomorrow when Vault Service gets upgraded to x.0.0, this library will be modified accordingly and versioned as x.0.0
- VaultSharp starts at e.g. 2.3.0 matching the Vault Server exactly, and then can go 2.3.0001, 2.3.0002 etc. for bug fixes etc. within 2.3.0 of Vault.
- Another thing to note is that, empirically, VaultSharp and Vault have been amazingly compatible even with great versioning differences. Kudos to the Vault team.
- Absolutely. VaultSharp is a .NET Library.
- This means, apart from using it in your C#, VB.NET, J#.NET and any .NET application, you can use it in PowerShell automation as well.
- Load up the DLL in your PowerShell code and execute the methods. PowerShell can totally work with .NET Dlls.
- The methods are async as the defacto implementation. The recommended usage.
- However, there are innumerable scenarios where you would continue to want to use it synchronously.
- For all those cases, there are various options available to you.
- There is a lot of discussion around the right usage, avoiding deadlocks etc.
- This library allows you to set the 'continueAsyncTasksOnCapturedContext' option when you initialize the client.
- It is an optional parameter and defaults to 'false'
- Setting it to false, allows you to access the .Result property of the task with reduced/zero deadlock issues.
- There are other ways as well to invoke it synchronously, and I leave it to the users of the library. (Task.Run etc.)
- But please note that as much as possible, use it in an async manner.
- If the above documentation doesn't help you, feel free to create an issue or email me. https://github.com/rajanadar/VaultSharp/issues/new