LogoLogo
HomePricingDocumentation
  • 💿Getting Started
    • Installation and Project Setup
    • Hello Perigee!
    • Perigee Application Design
    • Hello Configuration
    • Hello Logs
    • Hello Integration
    • Troubleshooting
    • Case Studies
  • 📃License + Notice
    • 📂Licensing
    • Notice of Third Party Agreements
  • 🚀Perigee and Beyond
    • Extending - Threads
    • Extending - Loaders
    • ⏳All about CRON
  • 🔮API Generation
    • What is API Generation?
    • API Builder
  • 🗺️Architecting YOUR App
    • Design and Requirements
    • Define Sources
    • Requirements
  • 🧩Core Modules
    • 🌐PerigeeApplication
    • 🪡Thread Registry
    • Event Sources
      • Scheduled/Logic
        • CRON Thread
        • Scheduler
        • Sync Agent
      • Watchers
        • SalesForce
        • Sharepoint
        • Directory Watch
        • Directory Notifier
        • IMAP
    • Credential Management
      • Connection Strings
      • Custom Refresh Logic
      • RestSharp Authenticator
      • Credential Store SDK
      • ⁉️Troubleshooting Credentials
    • Integration Utilities
      • HTTP(S) - RestSharp
      • Transaction Coordinator
      • Limiter
      • Watermarking
    • Alert Managers
      • SMS
      • Email
      • Discord
      • Teams
    • File Formats
      • Excel
      • CSV
    • 📁File System Storage
      • File Revision Store
      • Concurrent File Store
      • FileSync + Cache
    • Third Party
      • SmartSheets
      • Microsoft Graph
    • Perigee In Parallel
      • Parallel Processing Reference
      • Extensions
      • GroupProcessor
      • SingleProcessor
    • 🧱Utility Classes
      • Metrics
      • F(x) Expressions
      • Multi-Threaded Processor (Scatter Gather)
      • OpenAI - GPT
      • XML Converter
      • Dynamic Data Table
      • Debounce
      • Thread Conditions
      • Perigee Utility Class
      • Network Utility
      • Lists
      • FileUtil
      • Inclusive2DRange
      • Strings, Numbers, Dates
      • Nested Sets
      • Behavior Trees
      • JsonCompress
      • Topological Sorting
      • DBDownloader
    • 🈁Bit Serializer
  • 📣Examples and Demos
    • API + Perigee
    • 📰Excel Quick Load
    • SalesForce Watcher
    • Report Scheduler
    • Agent Data Synchronization
    • 📩IMAP Echo bot
    • Watch and load CSVs
    • Graph Delegated Authorization + DataVerse
    • Coordinator Demo
    • Azure Service Bus
    • QuickBooks Online
  • 📘Blueprints
    • Perigee With .NET Hosting
    • Web Host Utilities
    • 🔌Plugin Load Context
  • 🎞️Transforms
    • 🌟What is Transforms?
    • 📘Terminology
    • 🦾The Mapping Document
    • 👾Transformation Process
    • 😎Profile
    • 🎒Automation
      • 🕓Package Options
      • 🔳Configuration
    • 🔧Utilities
      • 🧹Clean
      • 📑Map File
      • 🔎File Identification
      • 🗺️Map Generation
      • 🪅Insert Statement Generation
  • 🗃️Transform SDK
    • 👋Quick Start Guide
    • 🥳MapTo
    • 🔌Authoring Plugins
      • 🔘File IO Process
      • 📢Data Quality
      • 🟢Transform Process
    • SDK Reference
      • 🔘FileIOProcessData
      • 📢DataQualityContext
      • 🎛️TransformDataContext
      • 🏅TransformResult
Powered by GitBook
On this page
  • Registering
  • RegisterRefresh
  • RegisterConnectionString
  • RegisterSalesForceJWT
  • Configuration
  • Configure
  • CredentialsToBytes
  • ConvertDictionaryToBytes / ConvertBytesToDictionary
  • DecryptCredentialFileAndRevert
  • Retrieve
  • GetCredential
  • GetCredential_ConnectionString
  • GetCredentialsByAuthorization
  • GetRefreshToken
  • PeekCredential
  • RefreshAuthorizationCode
  • Awaiting
  • Contains / Query
  • ContainsRefresh
  • ContainsCredential
  • Query credentials with predicate
  • Invalidation
  • InvalidateCredential
  • CredentialStoreItem
  • isExpired(int bufferSeconds = 300)
  • DecodeJWT(string token)
Export as PDF
  1. Core Modules
  2. Credential Management

Credential Store SDK

Below are the SDK methods tied to a credential and how they are called.

Registering

RegisterRefresh

This is the primary method for registering a refresh action.

CredentialStore.RegisterRefresh("SuperCredential", (o) => {

        //Call third party API
        //Reach out to database
        //Request keys from AWS
        //Do anything you need to get authorization details

        //Then return either a good credential:
        return new CredentialStoreItem() { 
            Expiration = DateTimeOffset.Now.AddMinutes(60),
            Authorization = "ABCDEFG",
            Scope = "offline.access",
            StoreA = "Custom ValueStore"
        };

        //Or a faulted one:
        return new FaultedCredentialStoreItem("External ERROR", new Exception("Exception thrown while trying to get credential!!!"), retry: true);
    });

The (o) => action callback is the refreshParam optionally supplied by calling GetCredential(). It is not required, but can be optionally used for custom logic

RegisterConnectionString

To register a connection string as a credential, which is a great way to support hot-reloading:

PerigeeApplication.ApplicationNoInit("ConnectionStrings", (c) => {

    //Register the connection string, or with the shortcut
    c.RegisterConnectionString("DB", "devServer");
    CredentialStore.RegisterConnectionString("DB", "devServer");
    
});

The AppSettings.json file:

"ConnectionStrings": {
      "devServer": "data source=host;initial catalog=database; User Id=user; Password=abc"
}

RegisterSalesForceJWT

This is the way you register a SalesForce JWT Authentication method.

CredentialStore.RegisterSalesForceJWT("SFJWT", 
"username", "consumerKey", 
new X509Certificate2("SF.pfx", "ABCD123"), 
"login");

Configuration

Configure

Configure is how we setup credential encryption, credential backup and restore policies.

Encryption

Supplying AES Keys will tell Perigee to use an encrypted credential store file. Even if you're already running without encryption, Perigee will detect the request to encrypt and convert the credential file before starting up.

Backup and restore

The initializationCallback and writeCallack can be used to effectively back up and restore your credential file remotely.

Every time a new credential file is written the writeCallback is called, this is your opportunity to store that elsewhere, even in a database blob object or on the cloud.

Every time the application starts up and NO credential file is present, the initializationCallback is called. This allows you to restore a credential file written elsewhere.

Here's an example of setting up your Perigee Application with credential encryption, backup and restore.

PerigeeApplication.ApplicationNoInit("Credentials", (c) => {
  //If calling configure, do so FIRST in the callback.
  
  // Call Configure, Perigee will auto convert non encrypted store to encrypted store
  CredentialStore.Configure(
    initializationCallback: () =>
    {
        //When there are no credentials, restore from remote backup (in this case another file on the hard drive, but it could be a database too)
        return CredentialStore.ConvertBytesToDictionary(File.ReadAllBytes(@"C:\temp\credentialbaks\credentials.pce"), AESKey, AESIV);
    }, 
    writeCallack: (bytes) =>
    {
        //Put the credential bytes anywhere else!
        FileRevisionStore.SaveFile(@"C:\temp\credentialbaks\credentialsBackup.pce", bytes);
    }, 
    AES32Key: AESKey, //Supplying AESKey and AESIV will encrypt the credentials
    AES16IV: AESIV);  //Supplying AESKey and AESIV will encrypt the credentials
});

//To get a new AESKey: AesCrypto.GetNewRandom(32, false)
//To get a new AESIV: AesCrypto.GetNewRandom(16, false)
//Or generate AES256 keys on your own!

Configure should be called FIRST after instanciating a perigee application.

CredentialsToBytes

This converts all the current credentials to a byte array.

If AES keys are provided, the bytes are encrypted.

If they are not provided, the bytes are compressed only.

CredentialStore.CredentialsToBytes(string AES32Key, string AES16IV)

ConvertDictionaryToBytes / ConvertBytesToDictionary

This converts a dictionary of credentials to an optionally encrypted byte array.

If AES keys are provided, the bytes are encrypted.

If they are not provided, the bytes are compressed only.

CredentialStore.ConvertDictionaryToBytes(
Dictionary<string, CredentialStoreItem> dictionary, 
string AES32Key, string AES16IV)

The inverse of this operation works exactly the same way:

CredentialStore.ConvertBytesToDictionary(
byte[] bytes, 
string AES32Key, string AES16IV)

DecryptCredentialFileAndRevert

If you're attempting to decrypt the encrypted credential file and revert back to using a non encrypted file, please call this before application start once, then remove. It will revert back the encryption in place.

The AES Key and IV will need to be supplied.

The altPath is a pointer to revert a different encrytped credential file than the default path. It's optional to supply this value

DecryptCredentialFileAndRevert(
string AES32Key, string AES16IV, 
string altPath = null)

Retrieve

GetCredential

To get a credential again at a later time, call GetCredential(). It will go through the process of synchronously locking and retrieving that credential and re-authorizing if needed.

//Use default settings
CredentialStore.GetCredential("SuperCredential"); 

//Set all settings on retrieval 
CredentialStore.GetCredential("SuperCredential", 
    maxRetries: 3, 
    retryMS: 1000, 
    expireTimeBufferSeconds: 600,
    disableRefresh: false, 
    object refreshParam: "Token");

The optional parameters are as follows:

  • maxRetries - If a refresh action returns a faulted credential then it defines the number of times a credential can attempt to "re-retrieve" it.

  • retryMS - How many milliseconds between retry attempts.

  • expireTimeBufferSeconds - How many seconds to buffer the expiration so an early refresh is called. Very useful to prevent a lapse in operation.

  • disableRefresh - If true, it will ONLY return the credential if it exists and it will not refresh or renew it. Useful for pulling expired credentials.

  • refreshParam - an object that can be passed to the registered refresh. Useful for supplying a one time use authorization token, or additional details to customize the way the refresh happens.

GetCredential_ConnectionString

To get a credential of type ConnectionStringCredentialStoreItem:

CredentialStore.GetCredential_ConnectionString("DB");

GetCredentialsByAuthorization

If you want to know what credentials have/share an authorization property:

var ienumerable = CredentialStore.GetCredentialsByAuthorization("authorizationTokenOrCode");

GetRefreshToken

Get a refresh token from a credential, even if that credential is expired.

CredentialStore.GetRefreshToken("credName");

PeekCredential

Will retrieve a credential without refreshing it, if it is invalid.

CredentialStore.PeekCredential("credName");

RefreshAuthorizationCode

Passes an authorization code the named refresh.

CredentialStore.RefreshAuthorizationCode("credName", "authCode");

//This is a shorthand helper method that is simply: 
//    GetCredential(name, 2, refreshParam: code)

Awaiting

You can await valid credentials, which is useful when waiting on a refresh or awaiting user interaction to authenticate a client. This method is async and can be awaited.

It pulls the credential once attempting to refresh it, if that fails then pulls it again on a timer with disableRefresh:true, meaning it won't try to refresh the credential and will wait on a valid credential.

await CredentialStore.AwaitValidCredential("name", CancelToken);

Contains / Query

ContainsRefresh

Returns true if a refresh action is registered for this credential name.

CredentialStore.ContainsRefresh("credName");

ContainsCredential

Returns true if the credentials exists, OR a refresh action is tied to that name.

CredentialStore.ContainsCredential("credName");

Query credentials with predicate

You can query all credentials without calling the refresh actions by using the ByPredicate method.

CredentialStore.GetCredentialsByPredicate(f => f.Name.Contains("Test"));

Invalidation

InvalidateCredential

Invalidation simply caused the credential's expiration to be set to DateTimeOffset.MinValue and then forces an immediate persist. Any future call to GetCredential() will force a refresh since it is now force-expired.

CredentialStore.InvalidateCredential("credName");

CredentialStoreItem

The Item has several properties you may use:

Name => Name of the credential. (don't set this!) 
Key => A key value.
Value=> A "Value" value.
Scope => If there is a scope associated with the credential.
Environment => What environment, or host does this belong to?
Authorization => a string, authorization, code, or token.
RefreshToken => If the OAUTH2 flow contains a refresh token, store it here.
Attributes => a dictionary of custom attributes, feel free to add whatever here.
Expiration => DateTimeOffset of the expiration of this credential. 

//Custom Store fields
StoreA => A custom field for any value
StoreB => A custom field for any value
StoreC => A custom field for any value

//For faulted
isFaulted => If the credential is a "Faulted" type
FaultReason => Fill this out with more information about why it was faulted
ExceptionGiven => If there was an exception thrown that is associated with the fault.

isExpired(int bufferSeconds = 300)

You can check if a credential is expired, or is about to expire by supplying the bufferSeconds parameter.

// Will check if the credential is or will expire in the next 2 minutes
item.isExpired(120); 

DecodeJWT(string token)

This will decode a JWT token into the JSON string of the body.

item.DecodeJWT(item.Authorization); 

PreviousRestSharp AuthenticatorNextTroubleshooting Credentials

Last updated 1 year ago

This is automatically created as part of the SalesForce client included in Perigee. See the for more info.

To remove encryption after encrypting, see the call below

SalesForce page
DecryptAndRevert
🧩
Page cover image