All pages
Powered by GitBook
1 of 1

Loading...

.NET SDK

Detailed .Net SDK docs for Keeper Secrets Manager

Download and Installation

Prerequisites

dotnet add package Keeper.SecretsManager

Source Code

Find the .Net source code in the

Using the SDK

Initialize Storage

Using token only to generate a new config (for later usage) requires at least one read operation to bind the token and fully populate config.json

In order to retrieve secrets, you must first initialize the local storage on your machine.

Example Usage

Secrets Manager Options

Retrieve Secrets

Response

Type: KeeperSecrets

Object containing all Keeper records, or records that match the given filter criteria

Example Usage

Retrieve all Secrets

Retrieve Secrets by Title

Parameter
Type
Required
Description

Example Usage

Retrieve Values from a Secret

Retrieve a Password

Field types are based on the Keeper . For a detailed list of available fields based on the Keeper Record Type, see the command in Keeper Commander.

Retrieve Other Fields Using Keeper Notation

See to learn about Keeper Notation format and capabilities

Retrieve TOTP Code

Update Values in a Secret

Record update commands don't update local record data on success (esp. updated record revision) so any consecutive updates to an already updated record will fail due to revision mismatch. Make sure to reload all updated records after each update batch.

Save Changes to a Secret

Use UpdateSecret to save changes made to a secret record. Changes will not be reflected in the Keeper Vault until UpdateSecret is performed.

Update a Field Value

Generate a Random Password

Parameter
Type
Required
Default

Each parameter indicates the min number of a type of character to include. For example, 'uppercase' indicates the minimum number of uppercase letters to include.

Download a File

Response

Type: ByteArray

ByteArray of file for download

Download a Thumbnail

Response

Type: ByteArray

ByteArray of thumbnail for download

Upload a File

Upload File:

Parameter
Type
Required
Description

Creating the Keeper File Upload Object:

Parameter
Type
Required
Description

Example Usage

Create a Secret

Prerequisites:

  • Shared folder UID

    • Shared folder must be accessible by the Secrets Manager Application

    • You and the Secrets Manager application must have edit permission

Parameter
Type
Required
Defaut

Delete a Secret

The .Net KSM SDK can delete records in the Keeper Vault.

Parameter
Type
Required

Caching

To protect against losing access to your secrets when network access is lost, the .Net SDK allows caching of secrets to the local machine in an encrypted file.

Setup and Configure Cache

In order to setup caching in the .Net SDK, include a caching post function as the second argument when instantiating aSecretsManagerOptions object.

The .Net SDK includes a default caching function cachingPostFunction which stores cached queries to a file.

Folders

Folders have full CRUD support - create, read, update and delete operations.

Read Folders

Downloads full folder hierarchy.

Response

Type: KeeperFolder[]

Example Usage

Create a Folder

Requires CreateOptions and folder name to be provided. The folder UID parameter in CreateOptions is required - UID of a shared folder, while sub-folder UID is optional and if missing, a new regular folder is created directly under the parent (shared folder). There's no requirement for the sub-folder to be a direct descendant of the parent shared folder - it could be many levels deep.

Parameter
Type
Required
Default
Description

Example Usage

Update a Folder

Updates the folder metadata - currently folder name only.

Parameter
Type
Required
Default
Description

Example Usage

Delete Folders

Removes a list of folders. Use forceDeletion flag to remove non-empty folders.

When using forceDeletion avoid sending parent with its children folder UIDs. Depending on the delete order you may get an error - ex. if parent force-deleted child first. There's no guarantee that list will always be processed in FIFO order.

Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.

Parameter
Type
Required
Default
Description

Example Usage

Proxy support

.NET SDK supports setting proxy through environment variables and passing proxy url to SecretsManagerOptions directly

Keeper recommends using environment variables for proxy settings. This approach keeps configuration details out of code, ensures consistency across tools and environments, and simplifies deployment and maintenance

Example usage through environment variables

Example usage passing url to SecretsManagerOptions

hostName

String

Optional

null

false

proxyUrl

String

Optional

null

Optional

0

digits

int

Optional

0

specialCharacters

int

Optional

0

Yes

The File to upload

Yes

The mime type of data in the file. 'application/octet-stream' for example

data

byte[]

Yes

File data as bytes

There must be at least one record in the shared folder
  • Created records and record fields must be formatted correctly

    • See the for expected field formats for each record type

  • TOTP fields accept only URL generated outside of the KSM SDK

  • After record creation, you can upload file attachments using UploadFile

  • KeeperRecordData

    Yes

    Parameter
    Type
    Required
    Defaut

    options

    SecretsManagerOptions

    Yes

    createOptions

    CreateOptions

    Yes

    This example creates a login type record with a login value and a generated password.

    Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager has access to.

    This example creates a record with a custom record type.

    Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager has access to.

    The parent and sub-folder UIDs

    folderName

    string

    Yes

    The Folder name

    folders

    KeeperFolder[]

    No

    null

    List of folders to use in the search for parent and sub-folder from CreateOptions

    The folder UID

    folderName

    string

    Yes

    The new folder name

    folders

    KeeperFolder[]

    No

    null

    List of folders to use in the search for parent folder

    The folder UID list

    forceDeletion

    bool

    No

    false

    Force deletion of non-empty folders

    Parameter

    Type

    Required

    Default

    Description

    storage

    KeyValueStorage

    Yes

    clientKey

    String

    Optional

    null

    Parameter

    Type

    Required

    Default

    storage

    KeyValueStorage

    Yes

    queryFunction

    String

    Optional

    null

    allowUnverifiedCertificate

    Bool

    Parameter

    Type

    Required

    Default

    Description

    options

    SecretsManagerOptions

    Yes

    Storage and query configuration

    recordsFilter

    List<String>

    Optional

    Empty List

    options

    SecretsManagerOptions

    Yes

    Preconfigured options

    recordTitle

    string

    Yes

    Record title to search for

    Parameter

    Type

    Required

    Default

    Description

    secrets

    KeeperSecrets

    Yes

    Secrets to query

    notation

    string

    Yes

    Parameter

    Type

    Required

    Default

    Description

    url

    string

    Yes

    TOTP Url

    Parameter

    Type

    Required

    Default

    Description

    options

    SecretsManagerOptions

    Yes

    Storage and query configuration

    Parameter

    Type

    Required

    Default

    Description

    fieldType

    string

    Yes

    The field to update

    value

    object

    Yes

    length

    int

    Optional

    64

    lowercase

    int

    Optional

    0

    uppercase

    Parameter

    Type

    Required

    Default

    Description

    file

    KeeperFile

    Yes

    File to download

    Parameter

    Type

    Required

    Default

    Description

    file

    KeeperFile

    Yes

    File with thumbnail to download

    options

    SecretsManagerOptions

    Yes

    Storage and query configuration

    ownerRecord

    KeeperRecord

    Yes

    The record to attach the uploaded file to

    file

    name

    string

    Yes

    What the name of the file will be in Keeper once uploaded

    title

    string

    Yes

    What the title of the file will be in Keeper once uploaded

    type

    options

    SecretsManagerOptions

    Yes

    folderUid

    string

    Yes

    smOptions

    SecretsManagerOptions

    Yes

    recordsUids

    string[]

    Yes

    options

    SecretsManagerOptions

    Yes

    Preconfigured options

    createOptions

    CreateOptions

    Yes

    options

    SecretsManagerOptions

    Yes

    Preconfigured options

    folderUid

    string

    Yes

    options

    SecretsManagerOptions

    Yes

    Preconfigured options

    folderUids

    string[]

    Yes

    GitHub repository
    record-type-info
    Keeper Notation documentation

    Optional

    Record search filters

    Field query in dot notation format

    Value to set the field to

    int

    KeeperFileUpload

    string

    record

    SecretsManagerClient.CreateSecret2(options, createOptions, record, folders)
    var newRecord = new KeeperRecordData{type = "login", title = "Sample KSM Record: C#"};
    
    newRecord.fields = new[]
    {
        new KeeperRecordField { type = "login", value = new[] { "My Username" } },
        new KeeperRecordField { type = "password", value = new[] { CryptoUtils.GeneratePassword() } },
    };
    newRecord.notes = "This is a C# record creation example";
    
    var recordUid = await SecretsManagerClient.CreateSecret(options, folderUid, newRecord);
    var newRecord = new KeeperRecordData();
    newRecord.type = "Custom Login";
    newRecord.title = "Sample Custom Type KSM Record: C#";
    newRecord.fields = new[]
    {
        new KeeperRecordField { 
            type = "host", 
            value = new[] 
            {
                new Dictionary<string, string>
                {
                    { "hostName", "127.0.0.1"},
                    { "port", "8080"}
                }
            },
            label = "My Custom Host lbl",
            required = true
        },
        
        new KeeperRecordField { 
            type = "login", 
            value = new[] { "[email protected]" }, 
            required = true, 
            label = "My Custom Login lbl"
        },
        
        new KeeperRecordField
        {
            type = "password", 
            value = new[] { CryptoUtils.GeneratePassword() }, 
            required = true, 
            label = "My Custom Password lbl"
        },
        
        new KeeperRecordField
        {
            type = "url",
            value = new[] { "http://localhost:8080/login" },
            label = "My Login Page",
            required = true
        },
        
        new KeeperRecordField { 
            type = "securityQuestion", 
            value = new[]
            {
                new Dictionary<string, string>
                {
                    {"question", "What is one plus one (write just a number)"}, 
                    { "answer", "2" }
                }
            }, 
            label = "My Question 1",
            required = true
        },
        
        new KeeperRecordField { 
            type = "phone", 
            value = new[]
            {
                new Dictionary<string,string>
                {
                    { "region", "US" },
                    { "number", "510-444-3333" },
                    { "ext", "2345" },
                    { "type", "Mobile" }
                }
            }, 
            label = "My Private Phone", 
            privacyScreen = true
        },
    
        new KeeperRecordField
        {
            type = "date", 
            value = new[] {(object) 1641934793000 }, 
            label = "My Date Lbl"
        },
        
        new KeeperRecordField { 
            type = "name", 
            value = new[]
            {
                new Dictionary<string, string>
                {
                    {"first", "John"},
                    {"middle", "Patrick"},
                    {"last", "Smith"}
                }
            },
            required = true
        },
        new KeeperRecordField
        {
            type = "oneTimeCode", 
            value = new[]
            {
                "otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example"
            }, 
            label = "My TOTP",
            required = true
        }
    };
    newRecord.notes = "\tThis custom type record was created\n\tvia Python SDK copied from https://docs.keeper.io/secrets-manager/secrets-manager/developer-sdk-library/.net-sdk";
    
    var recordUid = await SecretsManagerClient.CreateSecret(options, "[FOLDER_UID]", newRecord);
    
    SecretsManagerClient.InitializeStorage(storage: KeyValueStorage, clientKey: String? = null, hostName: String? = null)
    var storage = new LocalConfigStorage("ksm-config.json");
    SecretsManagerClient. InitializeStorage(storage, "[One Time Access Token]");
    // Using token only to generate a config (for later usage)
    // requires at least one access operation to bind the token
    //var options = new SecretsManagerOptions(storage);
    //await SecretsManagerClient.GetSecrets(options);
    SecretsManagerOptions(IKeyValueStorage storage, QueryFunction queryFunction = null, bool allowUnverifiedCertificate = false, string proxyUrl = null)
    GetSecrets(options: SecretsManagerOptions, recordsFilter: List<String> = emptyList()): KeeperSecrets
    var options = new SecretsManagerOptions(storage, testPostFunction);
    var secrets = GetSecrets(options);
    // get all matching records
    async Task<IEnumerable<KeeperRecord>> GetSecretsByTitle(SecretsManagerOptions options, string recordTitle)
    
    // get only the first matching record
    async Task<KeeperRecord> GetSecretByTitle(SecretsManagerOptions options, string recordTitle)
    using System;
    using System.Threading.Tasks;
    using SecretsManager;
    
    private static async Task getOneIndividualSecret()
    {
        var storage = new LocalConfigStorage("ksm-config.json");
        var options = new SecretsManagerOptions(storage);
        var records = (await SecretsManagerClient.GetSecretsByTitle(
                options, "My Credentials")
            ).Records;
        foreach (var record in records)
        {
            Console.WriteLine(record.RecordUid + " - " + record.Data.title);
            foreach (var field in record.Data.fields)
            {
                Console.WriteLine("\t" + field.label + " (" + field.type + "): [" + String.Join(", ", field.value) + "]");
            }
        }
    }
    secret.FieldValue("password")
    var storage = new LocalConfigStorage(configName);
    Console.WriteLine($"Local Config Storage opened from the file {configName}");
    if (clientKey != null)
        SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
    }
    var options = new SecretsManagerOptions(storage);
    //get secrets
    var secrets= (await SecretsManagerClient.GetSecrets(options)).Records;
    
    // get the password from the first secret
    var firstSecret= secrets[0];
    var password = firstSecret.FieldValue("password").ToString();
    GetValue(KeeperSecrets secrets, string notation)
    var storage = new LocalConfigStorage(configName);
    Console.WriteLine($"Local Config Storage opened from the file {configName}");
    if (clientKey != null)
        SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
    }
    var options = new SecretsManagerOptions(storage);
    //get secrets
    var secrets (await SecretsManagerClient.GetSecrets(options)).Records;
    
    // get login field value using dot notation
    var password = Notation.GetValue(secrets, "BediNKCMG21ztm5xGYgNww/field/login");
    CryptoUtils.GetTotpCode(string url)
    var storage = new LocalConfigStorage(configName);
    Console.WriteLine($"Local Config Storage opened from the file {configName}");
    if (clientKey != null)
        SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
    }
    var options = new SecretsManagerOptions(storage);
    //get secrets
    var secrets (await SecretsManagerClient.GetSecrets(options)).Records;
    
    // get TOTP url from a record
    var url = Notation.GetValue(secrets, "BediNKCMG21ztm5xGYgNww/field/OneTimeCode");
    
    // get TOTP code
    var totp = CryptoUtils.GetTotpCode(url);
    Console.WriteLine(totp.Code);
    UpdateSecret(options: SecretsManagerOptions, record: KeeperRecord);
    var options = SecretsManagerOptions(storage, testPostFunction)
    await SecretsManagerClient.UpdateSecret(options, secret);
    var storage = new LocalConfigStorage(configName);
    var options = new SecretsManagerOptions(storage);
    
    //get secrets
    var secrets = (await SecretsManagerClient.GetSecrets(options)).Records;
    
    // get the first secret
    var secret = secrets[0];
    
    // rotate password on the record
    secret.updateFieldValue("password", "MyNewPassword");
    //start a transaction
    await SecretsManagerClient.UpdateSecret(options, secret, UpdateTransactionType.Rotation);
    // rotate password on remote host
    success = rotateRemoteSshPassword("MyNewPassword");
    // complete the transaction - commit or rollback
    await SecretsManagerClient.CompleteTransaction(options, secret.RecordUid, rollback: !success);
    UpdateFieldValue(string fieldType, object value)
    var storage = new LocalConfigStorage(configName);
    Console.WriteLine($"Local Config Storage opened from the file {configName}");
    if (clientKey != null)
        SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
    }
    var options = new SecretsManagerOptions(storage);
    //get secrets
    var secrets= (await SecretsManagerClient.GetSecrets(options)).Records;
    
    // get the password from the first secret
    var firstSecret= secrets[0];
    
    // update the login field
    firstSecret.updateFieldValue("login", "My New Login");
    
    // update title and notes
    firstSecret.Data.title = "New Title";
    firstSecret.Data.notes = "New Notes";
    
    // save changes
    await SecretsManagerClient.UpdateSecret(options, firstSecret);
    
    CryptoUtils.GeneratePassword(int length, lowercase int, uppercase int, digits int, specialCharacters);
    // generate a random password
    var password = CryptoUtils.GeneratePassword();
    // update a record with the new password
    firstRecord.UpdateFieldValue("password", password);
    await SecretsManagerClient.UpdateSecret(options, firstRecord);
    DownloadFile(file: KeeperFile): ByteArray
    DownloadThumbnail(file: KeeperFile): ByteArray
    UploadFile(SecretsManagerOptions options, KeeperRecord ownerRecord, KeeperFileUpload file)
    KeeperFileUpload(string name, string title, string type, byte[] data)
    using System;
    using System.Threading.Tasks;
    using SecretsManager;
    
    private static async Task uploadFile()
    {
        // initalize storage and options
        var storage = new LocalConfigStorage("ksm-config.json");
        var options = new SecretsManagerOptions(storage);
        
        // get a record to attach the file to
        var records = (await SecretsManagerClient.GetSecrets(
                options, new[] { "XXX" })
            ).Records;
            
        var ownerRecord = records[0];
        
        // get file data to upload
        var bytes = await File.ReadAllBytesAsync("my-file.json");
        var myFile = new KeeperFileUpload(
            "my-file1.json", 
            "My File", 
            null, 
            bytes
        );
           
        // upload file to selected record                     
        await SecretsManagerClient.UploadFile(options, firstRecord, myFile);
        
    }
    SecretsManagerClient.CreateSecret(options, folderUid, record)
    DeleteSecret(smOptions, recordsUids);
    using SecretsManager;
    
    // setup secrets manager
    var storage = new LocalConfigStorage("ksm-config.json");
    //SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
    var smOptions = new SecretsManagerOptions(storage);
    
    // delete a specific secret by record UID
    await SecretsManagerClient.DeleteSecret(smOptions, new string[] {"EG6KdJaaLG7esRZbMnfbFA"});
    var options = new SecretsManagerOptions(storage, SecretsManagerClient.CachingPostFunction);
    var secrets = await SecretsManagerClient.GetSecrets(options);
    Task<KeeperFolder[]> GetFolders(SecretsManagerOptions options)
    using SecretsManager;
    
    var options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
    var folders = await SecretsManagerClient.GetFolders(options);
    Task<string> CreateFolder(SecretsManagerOptions options, CreateOptions createOptions, string folderName, KeeperFolder[] folders = null)
    public class CreateOptions {
        public string FolderUid { get; }
        public string SubFolderUid { get; }
    }
    public class KeeperFolder {
            public byte[] FolderKey { get; }
            public string FolderUid { get; }
            public string ParentUid { get; }
            public string Name { get; }
    }
    using SecretsManager;
    
    var options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
    var co := new CreateOptions("[PARENT_SHARED_FOLDER_UID]");
    var folderUid = await SecretsManagerClient.CreateFolder(options, co, "new_folder");
    Task UpdateFolder(SecretsManagerOptions options, string folderUid, string folderName, KeeperFolder[] folders = null)
    using SecretsManager;
    
    var options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
    await SecretsManagerClient.UpdateFolder(options, "[FOLDER_UID]", "new_folder_name");
    Task DeleteFolder(SecretsManagerOptions options, string[] folderUids, bool forceDeletion = false)
    using SecretsManager;
    
    var options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
    await SecretsManagerClient.DeleteFolder(options, new string[]{"[FOLDER_UID1]", "[FOLDER_UID2]"}, true);
    HTTPS_PROXY=http://user:[email protected]:3128 dotnet run
    var options = new SecretsManagerOptions(storage, null, false, "http://user:[email protected]:3128");

    record

    KeeperRecordData

    Yes

    folders

    KeeperFolder[]

    No

    Record Type
    documentation