### PKI Secrets Engine - Get Status of Certificate Tidying Process Source: https://rajanadar.github.io/VaultSharp Retrieves the status of the certificate tidying process. ```APIDOC ## PKI Secrets Engine - Get Status of Certificate Tidying Process ### Description Retrieves the status of the certificate tidying process. ### Method GET ### Endpoint /v1/pki/{mountpoint}/tidy ### Parameters #### Path Parameters - **mountpoint** (string) - Required - The mount path of the PKI secrets engine. ### Response #### Success Response (200) - **TidyState** (object) - The current state of the tidying process. ``` -------------------------------- ### Initialize VaultClient and Access Secrets Source: https://rajanadar.github.io/VaultSharp Demonstrates how to configure authentication, instantiate the client, and retrieve secrets from Key-Value and Consul engines. ```csharp // Initialize one of the several auth methods. IAuthMethodInfo authMethod = new TokenAuthMethodInfo("MY_VAULT_TOKEN"); // Initialize settings. You can also set proxies, custom delegates etc. here. var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(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 kv2Secret = await vaultClient.V1.Secrets.KeyValue.V2 .ReadSecretAsync(path: "secretPath", mountPoint: "mountPointIfNotDefault"); // Generate a dynamic Consul credential Secret consulCreds = await vaultClient.V1.Secrets.Consul.GetCredentialsAsync(consulRole, consulMount); string consulToken = consulCreds.Data.Token; ``` -------------------------------- ### GET /terraform/creds/:role Source: https://rajanadar.github.io/VaultSharp Generates or retrieves Terraform Cloud credentials based on the specified role. ```APIDOC ## GET /terraform/creds/:role ### Description Returns a Terraform Cloud token based on the given role definition. For Organization and Team roles, the token is reused until rotated; for User roles, a new token is generated per request. ### Method GET ### Endpoint /terraform/creds/:role ### Parameters #### Path Parameters - **role** (string) - Required - The name of the role. ### Response #### Success Response (200) - **Token** (string) - The Terraform Cloud token. - **TokenId** (string) - The ID of the generated token. ``` -------------------------------- ### Initialize VaultClient with AliCloud Auth Source: https://rajanadar.github.io/VaultSharp Configure the client using AliCloud authentication by providing the role name and identity request details. ```csharp // setup the AliCloud based auth to get the right token. IAuthMethodInfo authMethod = new AliCloudAuthMethodInfo(roleName, base64EncodedIdentityRequestUrl, base64EncodedIdentityRequestHeaders); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the AliCloud jwt ``` -------------------------------- ### Initialize VaultClient with Username and Password Source: https://rajanadar.github.io/VaultSharp Use this method for standard username and password authentication against a Vault server. ```csharp IAuthMethodInfo authMethod = new UserPassAuthMethodInfo(username, password); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the username/password. ``` -------------------------------- ### Undelete Secret Versions Source: https://rajanadar.github.io/VaultSharp Undeletes the data for the provided version and path in the key-value store, restoring it to be returned on get requests. ```csharp await vaultClient.V1.Secrets.KeyValue.V2.UndeleteSecretVersionsAsync(secretPath, versions); ``` -------------------------------- ### Initialize VaultClient with Custom Auth Source: https://rajanadar.github.io/VaultSharp Configure the VaultClient using a custom authentication method and the token provider delegate. ```csharp private VaultClient BuildVaultClient() { var vaultSettings = new VaultClientSettings( "https://MY_VAULT_SERVER:8200", new CustomAuthMethodInfo("vault-server-auth-method", GetCustomAuthMethodInfo) ); return new VaultClient(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. ``` -------------------------------- ### Initialize VaultClient with Token Auth Source: https://rajanadar.github.io/VaultSharp Standard initialization pattern for a Vault client using a static token. ```csharp // Initialize one of the several auth methods. IAuthMethodInfo authMethod = new TokenAuthMethodInfo("MY_VAULT_TOKEN"); // Initialize settings. You can also set proxies, custom delegates etc. here. var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); ``` -------------------------------- ### Initialize VaultClient with AppRole Auth Source: https://rajanadar.github.io/VaultSharp Configure the client using AppRole authentication by providing the role ID and secret ID. ```csharp // setup the AppRole based auth to get the right token. IAuthMethodInfo authMethod = new AppRoleAuthMethodInfo(roleId, secretId); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the app role and secret id. ``` -------------------------------- ### Accessing System Backend Methods in VaultSharp Source: https://rajanadar.github.io/VaultSharp Demonstrates the general pattern for accessing System backend features in VaultSharp. Replace `` with the specific method you intend to call. ```csharp vaultClient.V1.System. // The method you are looking for. ``` -------------------------------- ### Configure CloudFoundry Authentication Source: https://rajanadar.github.io/VaultSharp Initializes a VaultClient using CloudFoundry instance certificates and keys. ```csharp // setup the CloudFoundry based auth to get the right token. IAuthMethodInfo authMethod = new CloudFoundryAuthMethodInfo(roleName, instanceCertContent, instanceKeyContent); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the CloudFoundry jwt ``` -------------------------------- ### Force Immediate Vault Login Source: https://rajanadar.github.io/VaultSharp Invoke this method immediately after initialization to detect login failures at startup instead of during the first functional operation. ```csharp IVaultClient vaultClient = new VaultClient(vaultClientSettings); vaultClient.V1.Auth.PerformImmediateLogin(); ``` -------------------------------- ### Okta Auth Method Configuration Source: https://rajanadar.github.io/VaultSharp Configure Vault client for Okta authentication using username and password. ```csharp IAuthMethodInfo authMethod = new OktaAuthMethodInfo(userName, password); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the Okta username and password. ``` -------------------------------- ### Configure Kerberos Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Set up authentication using Kerberos. By default, it uses network credentials. You can also provide custom credentials. ```csharp IAuthMethodInfo authMethod = new KerberosAuthMethodInfo(); // uses network credential by default. // IAuthMethodInfo authMethod = new KerberosAuthMethodInfo(credentials); // use your own ICredentials var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the current ActiveDirectory/Kerberos identity. ``` -------------------------------- ### Token Creation Source: https://rajanadar.github.io/VaultSharp Create various types of tokens using the `CreateTokenAsync` method. Supports options for orphaned tokens, role-based tokens, and tokens with attached policies. ```csharp CreateTokenRequest request = new CreateTokenRequest(); // CreateTokenRequest has options to create orphaned tokens, role based tokens etc. with attached policies. Secret tokenData = await _authenticatedVaultClient.V1.Auth.Token.CreateTokenAsync(request); ``` -------------------------------- ### OCI Auth Method Configuration Source: https://rajanadar.github.io/VaultSharp Configure Vault client for OCI authentication. Requires specific request headers including signature details. ```csharp var requestHeaders = new Dictionary { {"date", new List { "Fri, 22 Aug 2019 21:02:19 GMT" } }, {"(request-target)", new List { "get /v1/auth/oci/login/devrole" } }, {"host", new List { "127.0.0.1" } }, {"content-type", new List { "application/json" } }, {"authorization", new List { "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\"" } } }; IAuthMethodInfo authMethod = new OCIAuthMethodInfo(roleName, requestHeaders); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the OCI entity. ``` -------------------------------- ### Configure Azure Authentication Source: https://rajanadar.github.io/VaultSharp Initializes a VaultClient using Azure JWT authentication. ```csharp // setup the Azure based auth to get the right token. IAuthMethodInfo authMethod = new AzureAuthMethodInfo(roleName, jwt); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the azure jwt ``` -------------------------------- ### Token Auth Method Login Source: https://rajanadar.github.io/VaultSharp Configure Vault client for authentication using a Vault token. ```csharp IAuthMethodInfo authMethod = new TokenAuthMethodInfo(vaultToken); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the vault token. ``` -------------------------------- ### Configure GitHub Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Use this snippet to set up authentication using a GitHub personal access token. Ensure the token has the necessary permissions. ```csharp IAuthMethodInfo authMethod = new GitHubAuthMethodInfo(personalAccessToken); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the github token. ``` -------------------------------- ### Okta Verify Push Challenge Source: https://rajanadar.github.io/VaultSharp Verify a push challenge from Okta. Requires a nonce and returns a challenge response. ```csharp string nonce = ""; var challengeResponse = await vaultClient.V1.Auth.Okta.VerifyPushChallengeAsync(nonce); var answer = challengeResponse.Data.CorrectAnswer; // verify this answer ``` -------------------------------- ### Generate AliCloud RAM Credentials Source: https://rajanadar.github.io/VaultSharp Generates dynamic RAM credentials based on a named role. ```csharp Secret aliCloudCreds = await vaultClient.V1.Secrets.AliCloud.GetCredentialsAsync(role); string accessKey = aliCloudCreds.Data.AccessKey; string secretKey = aliCloudCreds.Data.SecretKey; string securityToken = aliCloudCreds.Data.SecurityToken; string expiration = aliCloudCreds.Data.Expiration; ``` -------------------------------- ### Token Auth Method - Creation Source: https://rajanadar.github.io/VaultSharp Create new Vault tokens with various options. ```APIDOC ## Token Auth Method - Creation ### Description Create new Vault tokens with various options. ### Method POST ### Endpoint `/v1/auth/token/create` ### Request Body - **CreateTokenRequest** (object) - Required - An object containing parameters for token creation (e.g., `Orphan`, `Policies`, `Renewable`, `TTL`). ### Request Example ```csharp CreateTokenRequest request = new CreateTokenRequest(); // CreateTokenRequest has options to create orphaned tokens, role based tokens etc. with attached policies. Secret tokenData = await _authenticatedVaultClient.V1.Auth.Token.CreateTokenAsync(request); ``` ### Response #### Success Response (200) - **token** (object) - Contains information about the created token, including its accessor and ID. #### Response Example ```json { "request_id": "...", "lease_id": "", "renewable": false, "lease_duration": 0, "data": { "auth": { "client_token": "s.xxxxxxxxxxxxxxxxxxxx", "accessor": "a.xxxxxxxxxxxxxxxxxxxx", "policies": ["default", "my-policy"], "token_policies": ["default", "my-policy"], "metadata": { "role": "my-role" }, "lease_duration": 2764800, "renewable": true, "entity_id": "..." } }, "wrap_info": null, "warnings": [] } ``` ``` -------------------------------- ### Implement Custom Token Provider Source: https://rajanadar.github.io/VaultSharp Define a delegate that returns an AuthInfo object to provide a Vault token when using CustomAuthMethodInfo. ```csharp private Task GetCustomAuthMethodInfo() { var vaultOptions = new VaultOptions(); return Task.FromResult(new AuthInfo() { ClientToken = vaultOptions.VaultToken }); } ``` -------------------------------- ### RADIUS Auth Method Configuration Source: https://rajanadar.github.io/VaultSharp Configure Vault client for RADIUS authentication using username and password. ```csharp IAuthMethodInfo authMethod = new RADIUSAuthMethodInfo(userName, password); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the RADIUS username and password. ``` -------------------------------- ### Configure Google Cloud Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Set up authentication for Google Cloud using a role name and a JWT. This method maps the Google Cloud identity to Vault policies. ```csharp // setup the Google Cloud based auth to get the right token. IAuthMethodInfo authMethod = new GoogleCloudAuthMethodInfo(roleName, jwt); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the Google Cloud jwt ``` -------------------------------- ### Manage Static Database Roles Source: https://rajanadar.github.io/VaultSharp Endpoints for creating, reading, and deleting static database roles. These roles are used for managing pre-defined static credentials. ```csharp await vaultClient.V1.Secrets.Database.CreateStaticRoleAsync(roleName, roleRequest); await vaultClient.V1.Secrets.Database.ReadStaticRoleAsync(roleName); await vaultClient.V1.Secrets.Database.ReadAllStaticRolesAsync(); await vaultClient.V1.Secrets.Database.DeleteStaticRoleAsync(roleName); ``` -------------------------------- ### List Secrets (V1) Source: https://rajanadar.github.io/VaultSharp Returns a list of key names at the specified location. Folders are suffixed with /. ```APIDOC ## List Secrets (V1) ### Description 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. ### Request Example ```csharp Secret secret = await vaultClient.V1.Secrets.KeyValue.V1.ReadSecretPathsAsync(path); ListInfo paths = secret.Data; ``` ``` -------------------------------- ### Manage PKI certificates Source: https://rajanadar.github.io/VaultSharp Operations for generating, signing, revoking, and tidying certificates within the PKI secrets engine. ```csharp var certificateCredentialsRequestOptions = new CertificateCredentialsRequestOptions { // initialize }; Secret certSecret = await vaultClient.V1.Secrets.PKI.GetCredentialsAsync(pkiRoleName, certificateCredentialsRequestOptions); string privateKeyContent = certSecret.Data.PrivateKeyContent; ``` ```csharp var signCertificateRequestOptions = new SignCertificateRequestOptions { // initialize }; Secret certSecret = await vaultClient.V1.Secrets.PKI.SignCertificateAsync(pkiRoleName, signCertificateRequestOptions); string certificateContent = certSecret.Data.CertificateContent; ``` ```csharp Secret revoke = await vaultClient.V1.Secrets.PKI.RevokeCertificateAsync(serialNumber); long revocationTime = revoke.Data.RevocationTime; ``` ```csharp var request = new CertificateTidyRequest { TidyCertStore = false, TidyRevokedCerts = true }; await vaultClient.V1.Secrets.PKI.TidyAsync(request); ``` ```csharp var request = new CertificateAutoTidyRequest { TidyCertStore = false, TidyRevokedCerts = true }; await vaultClient.V1.Secrets.PKI.AutoTidyAsync(request); ``` ```csharp var tidyStatus = await vaultClient.V1.Secrets.PKI.GetTidyStatusAsync(); CertificateTidyState state = tidyStatus.Data.TidyState; ``` ```csharp var tidyStatus = await vaultClient.V1.Secrets.PKI.CancelTidyAsync(); CertificateTidyState state = tidyStatus.Data.TidyState; ``` -------------------------------- ### Write AWS Role Source: https://rajanadar.github.io/VaultSharp Creates or updates an AWS role. ```csharp var role = new CreateAWSRoleModel { CredentialType = AWSCredentialsType.federation_token, PolicyDocument = "{\"Version\": \"...\"}" }; await vaultClient.V1.Secrets.AWS.WriteRoleAsync("my-role-name", role); ``` -------------------------------- ### Generate KMIP Credentials Source: https://rajanadar.github.io/VaultSharp Creates a new client certificate tied to the given role and scope using the KMIP Secrets Engine. Requires scope name and role name. ```csharp Secret kmipCredentials = await vaultClient.V1.Secrets.Enterprise.KMIP.GetCredentialsAsync(scopeName, roleName); string certificateContent = kmipCredentials.Data.CertificateContent; string privateKeyContent = kmipCredentials.Data.PrivateKeyContent; ``` -------------------------------- ### List and read certificates Source: https://rajanadar.github.io/VaultSharp Retrieves lists of serial numbers or specific certificate details from the PKI engine. ```csharp var keys = await vaultClient.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")); ``` ```csharp var keys = await vaultClient.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")); ``` ```csharp var cert = await vaultClient.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); ``` ```csharp var caCert = await vaultClient.V1.Secrets.PKI.ReadCACertificateAsync(CertificateFormat.pem, mountpoint); Assert.NotNull(caCert.CertificateContent); ``` -------------------------------- ### Configure AWS IAM Authentication Source: https://rajanadar.github.io/VaultSharp Sets up AWS IAM authentication by generating signed STS headers and converting them to a base64 string for Vault. ```csharp // 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. var amazonSecurityTokenServiceConfig = new AmazonSecurityTokenServiceConfig(); // 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. AWSCredentials awsCredentials = new StoredProfileAWSCredentials(); // picks up the credentials from your profile. // AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey: "YOUR_ACCESS_KEY", secretKey: "YOUR_SECRET_KEY"); // explicit credentials var iamRequest = GetCallerIdentityRequestMarshaller.Instance.Marshall(new GetCallerIdentityRequest()); iamRequest.Endpoint = new Uri(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"); new AWS4Signer().Sign(iamRequest, amazonSecurityTokenServiceConfig, new RequestMetrics(), awsCredentials.GetCredentials().AccessKey, awsCredentials.GetCredentials().SecretKey); // This is the point, when you have the final set of required Headers. var iamSTSRequestHeaders = iamRequest.Headers; // Step 3: Convert the headers into a base64 value needed by Vault. var base64EncodedIamRequestHeaders = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(iamSTSRequestHeaders))); // Step 4: Setup the IAM AWS Auth Info. IAuthMethodInfo authMethod = new IAMAWSAuthMethodInfo(nonce: nonce, roleName: roleName, requestHeaders: base64EncodedIamRequestHeaders); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the aws-iam role ``` -------------------------------- ### Generate CloudFoundry Signature Source: https://rajanadar.github.io/VaultSharp Uses the CloudFoundrySignatureProvider helper class to generate a signature for authentication. ```csharp var signing_time = CloudFoundrySignatureProvider.GetFormattedSigningTime(DateTime.UtcNow); var signature = CloudFoundrySignatureProvider.GetSignature(signingTime, cfInstanceCertContent, roleName, cfInstanceKeyContent); ``` -------------------------------- ### Manage Database Roles Source: https://rajanadar.github.io/VaultSharp Endpoints for creating, reading, and deleting database roles. These operations manage the configuration of roles used for generating dynamic credentials. ```csharp await vaultClient.V1.Secrets.Database.CreateRoleAsync(roleName, roleRequest); await vaultClient.V1.Secrets.Database.ReadRoleAsync(roleName); await vaultClient.V1.Secrets.Database.ReadAllRolesAsync(); await vaultClient.V1.Secrets.Database.DeleteRoleAsync(roleName); ``` -------------------------------- ### Token Lookup (any Token) Source: https://rajanadar.github.io/VaultSharp Lookup information about any Vault Token using the `LookupAsync` method. Requires the token string as input. ```csharp string token = "token-for-which-you-need-info"; Secret tokenData = await _authenticatedVaultClient.V1.Auth.Token.LookupAsync(token); ``` -------------------------------- ### Okta Verify Push Challenge Source: https://rajanadar.github.io/VaultSharp Handle Okta Verify push challenge responses for authentication. ```APIDOC ## Okta Verify Push Challenge ### Description Handle Okta Verify push challenge responses for authentication. ### Method POST ### Endpoint `/v1/auth/okta/verify/challenge` ### Parameters #### Query Parameters - **nonce** (string) - Required - A nonce value provided by Okta. ### Request Body Not directly applicable, as the nonce is passed as a query parameter. ### Request Example ```csharp string nonce = ""; var challengeResponse = await vaultClient.V1.Auth.Okta.VerifyPushChallengeAsync(nonce); var answer = challengeResponse.Data.CorrectAnswer; // verify this answer ``` ### Response #### Success Response (200) - **data** (object) - Contains the verification result, including the `correct_answer`. #### Response Example ```json { "request_id": "...", "lease_id": "", "renewable": false, "lease_duration": 0, "data": { "correct_answer": "..." }, "wrap_info": null, "warnings": [] } ``` ``` -------------------------------- ### PKI Secrets Engine - Configure Automatic Tidying up of Certificate Storage Source: https://rajanadar.github.io/VaultSharp Configures automatic tidying of certificate storage. ```APIDOC ## PKI Secrets Engine - Configure Automatic Tidying up of Certificate Storage ### Description Configures automatic tidying of certificate storage. ### Method POST ### Endpoint /v1/pki/{mountpoint}/config/tidy ### Parameters #### Path Parameters - **mountpoint** (string) - Required - The mount path of the PKI secrets engine. #### Request Body - **TidyCertStore** (boolean) - Optional - Whether to automatically tidy the certificate store. - **TidyRevokedCerts** (boolean) - Optional - Whether to automatically tidy revoked certificates. ``` -------------------------------- ### Sign Batched Items with VaultSharp Source: https://rajanadar.github.io/VaultSharp Use this to sign multiple pieces of data in a single request. This is efficient for batch operations. Ensure the Vault client is authenticated and the key exists. ```csharp var signList = new SignRequestOptions { BatchInput = new List { new SignSingleInput {Base64EncodedInput = encodedText}, new SignSingleInput {Base64EncodedInput = encodedText2}, new SignSingleInput {Base64EncodedInput = encodedText3} }, SignatureAlgorithm = SignatureAlgorithm.Pkcs1v15, MarshalingAlgorithm = MarshalingAlgorithm.Asn1 }; var signResponse = await _authenticatedVaultClient.V1.Secrets.Transit.SignDataAsync(HashAlgorithm.sha2_256, keyName, signList); ``` -------------------------------- ### Configure Kubernetes Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Set up authentication for Kubernetes using a role name and a JWT. This method maps the Kubernetes service account to Vault policies. ```csharp // setup the Kubernetes based auth to get the right token. IAuthMethodInfo authMethod = new KubernetesAuthMethodInfo(roleName, jwt); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the Kubernetes jwt ``` -------------------------------- ### Configure AWS Lease Source: https://rajanadar.github.io/VaultSharp Configures lease settings for the AWS secrets engine. ```csharp var leaseConfigModel = new AWSLeaseConfigModel { Lease = "36h", MaximumLease = "72h" }; await vaultClient.V1.Secrets.AWS.ConfigureLeaseAsync(leaseConfigModel); ``` -------------------------------- ### Configure AWS EC2 Authentication Source: https://rajanadar.github.io/VaultSharp Initializes a VaultClient using AWS EC2 authentication with either PKCS7 or identity/signature parameters. ```csharp // setup the AWS-EC2 based auth to get the right token. IAuthMethodInfo authMethod = new EC2AWSAuthMethodInfo(pkcs7, null, null, nonce, roleName); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the aws-ec2 role ``` ```csharp // setup the AWS-EC2 based auth to get the right token. IAuthMethodInfo authMethod = new EC2AWSAuthMethodInfo(null, identity, signature, nonce, roleName); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the aws-ec2 role ``` -------------------------------- ### Generate Static DB Credentials Source: https://rajanadar.github.io/VaultSharp Generates a new set of static database credentials based on the specified named role. ```csharp Secret dbCreds = await vaultClient.V1.Secrets.Database.GetStaticCredentialsAsync(role); ``` -------------------------------- ### Backup Key Source: https://rajanadar.github.io/VaultSharp Backs up a key from the Transit Secrets Engine. The key must have been created with 'allow_plaintext_backup' set to true. ```csharp var backup = await _authenticatedVaultClient.V1.Secrets.Transit.BackupKeyAsync(keyName); string backupData = backup.Data.BackupData; ``` -------------------------------- ### Read AWS Lease Source: https://rajanadar.github.io/VaultSharp Returns current lease settings for the AWS secrets engine. ```csharp Secret lease = await vaultClient.V1.Secrets.AWS.GetLeaseConfigAsync(); ``` -------------------------------- ### Configure AWS Root IAM Credentials Source: https://rajanadar.github.io/VaultSharp Configures the root IAM credentials required for communication with AWS. ```csharp var configureRootIAMCredentialsModel = new ConfigureRootIAMCredentialsModel { AccessKey = "<>", SecretKey = "<>", Region = "<>" }; await vaultClient.V1.Secrets.AWS.ConfigureRootIAMCredentialsAsync(configureRootIAMCredentialsModel); ``` -------------------------------- ### Token Auth Method - Login Source: https://rajanadar.github.io/VaultSharp Authenticate with Vault using a pre-existing Vault token. ```APIDOC ## Token Auth Method - Login ### Description Authenticate with Vault using a pre-existing Vault token. ### Method POST (Implicitly, as part of client initialization) ### Endpoint `/v1/auth/token/login` (Implicit) ### Request Body Not directly applicable, as authentication is configured via `IAuthMethodInfo`. ### Request Example ```csharp IAuthMethodInfo authMethod = new TokenAuthMethodInfo(vaultToken); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); ``` ### Response Authentication is handled during client initialization. Subsequent operations will use the provided Vault token and its associated policies. ``` -------------------------------- ### Configure JWT/OIDC Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Configure authentication using JWT or OIDC. This requires a role name and a JWT, mapping the identity to Vault policies. ```csharp // setup the JWT/OIDC based auth to get the right token. IAuthMethodInfo authMethod = new JWTAuthMethodInfo(roleName, jwt); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the jwt ``` -------------------------------- ### Okta Auth Method Source: https://rajanadar.github.io/VaultSharp Authenticate with Vault using Okta identity. This method uses Okta username and password. ```APIDOC ## Okta Auth Method ### Description Authenticate with Vault using Okta identity. This method uses Okta username and password. ### Method POST (Implicitly, as part of client initialization) ### Endpoint `/v1/auth/okta/login` ### Request Body Not directly applicable, as authentication is configured via `IAuthMethodInfo`. ### Request Example ```csharp IAuthMethodInfo authMethod = new OktaAuthMethodInfo(userName, password); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); ``` ### Response Authentication is handled during client initialization. Subsequent operations will use the Okta-mapped Vault token/policies. ``` -------------------------------- ### Generate SSH credentials Source: https://rajanadar.github.io/VaultSharp Creates SSH credentials for a specific user and IP address. ```csharp Secret sshCreds = await vaultClient.V1.Secrets.SSH.GetCredentialsAsync(role, ipAddress, username); string sshKey = sshCreds.Data.Key; ``` -------------------------------- ### Certificate (TLS) Auth Method Configuration Source: https://rajanadar.github.io/VaultSharp Configure Vault client for TLS certificate authentication. The certificate must be in PKCS12 format. Optionally, a role name or full certificate chain can be provided. ```csharp // 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.pem var certificate = new X509Certificate2(your-p12-bytes, your-pass); IAuthMethodInfo authMethod = new CertAuthMethodInfo(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 = ; // IAuthMethodInfo authMethod = new CertAuthMethodInfo(x509Certificate2Collection); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the client certificate. ``` -------------------------------- ### OpenLDAP - Generate static role credentials Source: https://rajanadar.github.io/VaultSharp This endpoint offers the credential information for a given static-role. ```APIDOC ## OpenLDAP - Generate static role credentials ### Description This endpoint offers the credential information for a given static-role. ### Method GET ### Endpoint /v1/openldap/static-credentials/{role_name} ### Parameters #### Path Parameters - **role_name** (string) - Required - The name of the static role. ### Response #### Success Response (200) - **Username** (string) - The username for the static credentials. - **Password** (string) - The password for the static credentials. ### Request Example ```csharp Secret credentials = await vaultClient.V1.Secrets.OpenLDAP.GetStaticCredentialsAsync(roleName); string username = credentials.Data.Username; string password = credentials.Data.Password; ``` ``` -------------------------------- ### Injecting Custom HttpClient into VaultSharp Source: https://rajanadar.github.io/VaultSharp Shows how to provide a custom HttpClient instance to VaultSharp. VaultSharp will manage the Vault-specific URL and timeout settings for the provided handler. ```csharp var settings = new VaultClientSettings("http://localhost:8200", authMethodInfo) { Namespace = "mynamespace", MyHttpClientProviderFunc = handler => new HttpClient(handler) }; ``` -------------------------------- ### Generate Kubernetes Credentials Source: https://rajanadar.github.io/VaultSharp Generates dynamic Kubernetes credentials based on the given role definition. Requires role name and namespace. ```csharp Secret kubernetesCredentials = await vaultClient.V1.Secrets.Kubernetes.GetCredentialsAsync(ksRoleName, ksNamespace); string serviceAccountToken = kubernetesCredentials.Data.ServiceAccountToken; ``` -------------------------------- ### Hash Data String Source: https://rajanadar.github.io/VaultSharp Hashes input data using a specified algorithm. Supports base64 encoding for both input and output. ```csharp var hashOpts = new HashRequestOptions { Format = OutputEncodingFormat.base64, Base64EncodedInput = encodedStringToHash }; var hashResponse = await _authenticatedVaultClient.V1.Secrets.Transit.HashDataAsync(HashAlgorithm.sha2_256, hashOpts); var hashString = hashResponse.Data.HashSum; ``` -------------------------------- ### Certificate (TLS) Auth Method Source: https://rajanadar.github.io/VaultSharp Authenticate with Vault using client certificates (TLS). The certificate must be in PKCS12 format. ```APIDOC ## Certificate (TLS) Auth Method ### Description Authenticate with Vault using client certificates (TLS). The certificate must be in PKCS12 format. ### Method POST (Implicitly, as part of client initialization) ### Endpoint `/v1/auth/cert/login` ### Request Body Not directly applicable, as authentication is configured via `IAuthMethodInfo`. ### Request Example ```csharp // 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.pem var certificate = new X509Certificate2(your-p12-bytes, your-pass); IAuthMethodInfo authMethod = new CertAuthMethodInfo(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 = ; // IAuthMethodInfo authMethod = new CertAuthMethodInfo(x509Certificate2Collection); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); ``` ### Response Authentication is handled during client initialization. Subsequent operations will use the certificate-mapped Vault token/policies. ``` -------------------------------- ### Configure LDAP Auth Method in VaultSharp Source: https://rajanadar.github.io/VaultSharp Configure authentication using LDAP credentials. This method maps the LDAP user to Vault policies. ```csharp IAuthMethodInfo authMethod = new LDAPAuthMethodInfo(userName, password); var vaultClientSettings = new VaultClientSettings("https://MY_VAULT_SERVER:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); // any operations done using the vaultClient will use the // vault token/policies mapped to the LDAP username and password. ``` -------------------------------- ### Trim Key Source: https://rajanadar.github.io/VaultSharp Trims a key to a minimum available version. Requires the key name and trim options. ```csharp var trimOptions = new TrimKeyRequestOptions { MinimumAvailableVersion = 2 }; await _authenticatedVaultClient.V1.Secrets.Transit.TrimKeyAsync(keyName, trimOptions); ``` -------------------------------- ### Generate Dynamic DB Credentials Source: https://rajanadar.github.io/VaultSharp Generates a new set of dynamic database credentials based on a named role. The generated username and password can then be used to connect to the database. ```csharp Secret dbCreds = await vaultClient.V1.Secrets.Database.GetCredentialsAsync(role); string username = dbCreds.Data.Username; string password = dbCreds.Data.Password; ``` -------------------------------- ### Read All AWS Roles Source: https://rajanadar.github.io/VaultSharp Retrieves a list of all configured AWS roles. ```csharp Secret roles = await vaultClient.V1.Secrets.AWS.ReadAllRolesAsync(); List names = roles.Data; ``` -------------------------------- ### List Secrets (V1) Source: https://rajanadar.github.io/VaultSharp Retrieves a list of secret key names at a specified path. Folders are suffixed with '/'. This operation does not return secret values and performs no policy-based filtering on key names. ```csharp Secret secret = await vaultClient.V1.Secrets.KeyValue.V1.ReadSecretPathsAsync(path); ListInfo paths = secret.Data; ``` -------------------------------- ### Sign Single Item with VaultSharp Source: https://rajanadar.github.io/VaultSharp Use this to sign a single piece of data using a specified key and algorithm. Ensure the Vault client is authenticated and the key exists. ```csharp var signOptions = new SignRequestOptions { Base64EncodedInput = encodedText, SignatureAlgorithm = SignatureAlgorithm.Pkcs1v15, MarshalingAlgorithm = MarshalingAlgorithm.Asn1 }; var signResponse = await _authenticatedVaultClient.V1.Secrets.Transit.SignDataAsync(HashAlgorithm.sha2_256, keyName, signOptions); ``` -------------------------------- ### List Secrets (V2) Source: https://rajanadar.github.io/VaultSharp Retrieves a list of secret key names at a specified path within the V2 Key/Value secrets engine. Similar to V1, folders are suffixed with '/', and secret values are not returned. ```csharp Secret secret = await vaultClient.V1.Secrets.KeyValue.V2.ReadSecretPathsAsync(path); ListInfo paths = secret.Data; ``` -------------------------------- ### Write Secret Metadata (V2) Source: https://rajanadar.github.io/VaultSharp Creates or updates the custom metadata for a secret at a specified path in the V2 Key/Value secrets engine. ```csharp var writeCustomMetadataRequest = new CustomMetadataRequest { CustomMetadata = new Dictionary { { "owner", "system"}, { "expired_in", "20331010"} } }; await _authenticatedVaultClient.V1.Secrets.KeyValue.V2.WriteSecretMetadataAsync(path, writeCustomMetadataRequest, mountPoint: kv2SecretsEngine.Path); ``` -------------------------------- ### Secrets - List Secrets Source: https://rajanadar.github.io/VaultSharp This endpoint returns a list of secret entries at the specified location. Folders are suffixed with /. The input must be a folder; listing on a file will not return a value. The values themselves are not accessible via this command. ```APIDOC ## List Secrets ### Description Returns a list of secret entries at the specified location. Folders are suffixed with /. The input must be a folder; listing on a file will not return a value. The values themselves are not accessible via this command. ### Method GET ### Endpoint /secrets/cubbyhole/{folderPath} ### Parameters #### Path Parameters - **folderPath** (string) - Required - The path to the folder to list secrets from. ### Response #### Success Response (200) - **Data** (ListInfo) - Contains the list of secret paths. ### Request Example ```csharp Secret secret = await vaultClient.V1.Secrets.Cubbyhole.ReadSecretPathsAsync(folderPath); ListInfo paths = secret.Data; ``` ``` -------------------------------- ### AliCloud Secrets Engine API Source: https://rajanadar.github.io/VaultSharp Generates dynamic RAM credentials based on the named role. ```APIDOC ## GET /secrets/aliyun/credentials/{role} ### Description This endpoint generates dynamic RAM credentials based on the named role. ### Method GET ### Endpoint /secrets/aliyun/credentials/{role} ### Parameters #### Path Parameters - **role** (string) - Required - The name of the role for which to generate credentials. ### Response #### Success Response (200) - **AliCloudCredentials** (object) - Contains the AliCloud credentials. - **AccessKey** (string) - The Access Key ID. - **SecretKey** (string) - The Access Key Secret. - **SecurityToken** (string) - The security token (if applicable). - **Expiration** (string) - The expiration time of the credentials. ### Response Example ```json { "data": { "access_key": "", "secret_key": "", "security_token": "", "expiration": "" } } ``` ``` -------------------------------- ### List Secrets (V2) Source: https://rajanadar.github.io/VaultSharp Returns a list of key names at the specified location in V2. ```APIDOC ## List Secrets (V2) ### Description Returns a list of key names at the specified location. Folders are suffixed with /. ### Request Example ```csharp Secret secret = await vaultClient.V1.Secrets.KeyValue.V2.ReadSecretPathsAsync(path); ListInfo paths = secret.Data; ``` ``` -------------------------------- ### Encrypt Batched Items Source: https://rajanadar.github.io/VaultSharp Encrypts multiple items in a single request. Ensure all items are properly encoded. ```csharp var encryptOptions = new EncryptRequestOptions { BatchedEncryptionItems = new List { new EncryptionItem { Base64EncodedContext = encodedContext1, Base64EncodedPlainText = encodedPlainText1 }, new EncryptionItem { Base64EncodedContext = encodedContext2, Base64EncodedPlainText = encodedPlainText2 }, new EncryptionItem { Base64EncodedContext = encodedContext3, Base64EncodedPlainText = encodedPlainText3 }, } }; Secret encryptionResponse = await _authenticatedVaultClient.V1.Secrets.Transit.EncryptAsync(keyName, encryptOptions); string firstCipherText = encryptionResponse.Data.BatchedResults.First().CipherText; ``` -------------------------------- ### Manage RabbitMQ secrets Source: https://rajanadar.github.io/VaultSharp Generates dynamic credentials and manages roles for the RabbitMQ secrets engine. ```csharp Secret secret = await vaultClient.V1.Secrets.RabbitMQ.GetCredentialsAsync(roleName); string username = secret.Data.Username; string password = secret.Data.Password; ``` ```csharp var virtualHostName = "/"; var virtualHostPermission = new { write = ".*", read = ".*" }; var virtualHosts = new Dictionary() { { virtualHostName, virtualHostPermission } }; var virtualHostsJson = JsonSerializer.Serialize(virtualHosts); var role = new RabbitMQRole() { VHosts = virtualHostsJson } await vaultClient.V1.Secrets.RabbitMQ.CreateRoleAsync(roleName, role, mountPoint); await vaultClient.V1.Secrets.RabbitMQ.ReadRoleAsync(roleName, mountPoint); await vaultClient.V1.Secrets.RabbitMQ.DeleteRoleAsync(roleName, mountPoint); ``` -------------------------------- ### Verify Signature Single Item with VaultSharp Source: https://rajanadar.github.io/VaultSharp Use this to verify a single signature against the original data. Requires the data, the signature, the signature algorithm, and the key name. Ensure the Vault client is authenticated. ```csharp var verifyOptions = new VerifyRequestOptions { Base64EncodedInput = base64Input, Signature = signResponse.Data.Signature, SignatureAlgorithm = SignatureAlgorithm.Pkcs1v15, MarshalingAlgorithm = MarshalingAlgorithm.Asn1 }; var verifyResponse = await _authenticatedVaultClient.V1.Secrets.Transit.VerifySignedDataAsync(HashAlgorithm.sha2_256, keyname, verifyOptions); var isValid = verifyResponse.Data.Valid; ``` -------------------------------- ### Token Lookup (Calling Token) Source: https://rajanadar.github.io/VaultSharp Lookup information about the current Vault Token using the `LookupSelfAsync` method. ```csharp Secret tokenData = await _authenticatedVaultClient.V1.Auth.Token.LookupSelfAsync(); ```