

# Get a Secrets Manager secret value using .NET with client-side caching
<a name="retrieving-secrets_cache-net"></a>

When you retrieve a secret, you can use the Secrets Manager .NET-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-net-SecretCacheConfiguration.md#retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheItemTTL) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-net-ISecretCacheHook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following:
+ .NET Framework 4.6.2 or higher, or .NET Standard 2.0 or higher. See [Download .NET](https://dotnet.microsoft.com/en-us/download) on the Microsoft .NET website.
+ The AWS SDK for .NET. See [AWS SDKs](asm_access.md#asm-sdks).

To download the source code, see [Caching client for .NET](https://github.com/aws/aws-secretsmanager-caching-net ) on GitHub.

To use the cache, first instantiate it, then retrieve your secret by using `GetSecretString` or `GetSecretBinary`. On successive retrievals, the cache returns the cached copy of the secret.

**To get the caching package**
+ Do one of the following:
  + Run the following .NET CLI command in your project directory.

    ```
    dotnet add package AWSSDK.SecretsManager.Caching --version 1.0.6
    ```
  + Add the following package reference to your `.csproj` file.

    ```
    <ItemGroup>
        <PackageReference Include="AWSSDK.SecretsManager.Caching" Version="1.0.6" />
    </ItemGroup>
    ```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [SecretsManagerCache](retrieving-secrets_cache-net-SecretsManagerCache.md)
+ [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md)
+ [ISecretCacheHook](retrieving-secrets_cache-net-ISecretCacheHook.md)

**Example Retrieve a secret**  
The following code example shows a method that retrieves a secret named *MySecret*.  

```
using Amazon.SecretsManager.Extensions.Caching;

namespace LambdaExample 
{
    public class CachingExample 
    {
        private const string MySecretName ="MySecret";

        private SecretsManagerCache cache = new SecretsManagerCache();

        public async Task<Response>  FunctionHandlerAsync(string input, ILambdaContext context)
        {
            string MySecret = await cache.GetSecretString(MySecretName);
            
            // Use the secret, return success
            
        }
    }
}
```

**Example Configure the time to live (TTL) cache refresh duration**  
The following code example shows a method that retrieves a secret named *MySecret* and sets the TTL cache refresh duration to 24 hours.  

```
using Amazon.SecretsManager.Extensions.Caching;

namespace LambdaExample
{
    public class CachingExample
    {
        private const string MySecretName = "MySecret";
        
        private static SecretCacheConfiguration cacheConfiguration = new SecretCacheConfiguration
        {
            CacheItemTTL = 86400000
        };
        private SecretsManagerCache cache = new SecretsManagerCache(cacheConfiguration);
        public async Task<Response> FunctionHandlerAsync(string input, ILambdaContext context)
        {
            string mySecret = await cache.GetSecretString(MySecretName);

            // Use the secret, return success
        }
    }
}
```

# SecretsManagerCache
<a name="retrieving-secrets_cache-net-SecretsManagerCache"></a>

An in-memory cache for secrets requested from Secrets Manager. You use [GetSecretString](#retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretString) or [GetSecretBinary](#retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretBinary) to retrieve a secret from the cache. You can configure the cache settings by passing in a [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) object in the constructor. 

For more information, including examples, see [Get a Secrets Manager secret value using .NET with client-side caching](retrieving-secrets_cache-net.md).

## Constructors
<a name="retrieving-secrets_cache-net-SecretsManagerCache-constructors"></a>

`public SecretsManagerCache()`  
Default constructor for a `SecretsManagerCache` object.

`public SecretsManagerCache(IAmazonSecretsManager secretsManager)`  
Constructs a new cache using a Secrets Manager client created using the provided [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html). Use this constructor to customize the Secrets Manager client, for example to use a specific region or endpoint.  
**Parameters**    
secretsManager  
The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from.

`public SecretsManagerCache(SecretCacheConfiguration config)`  
Constructs a new secret cache using the provided [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md). Use this constructor to configure the cache, for example the number of secrets to cache and how often it refreshes.  
**Parameters**    
config  
A [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) that contains configuration information for the cache.

`public SecretsManagerCache(IAmazonSecretsManager secretsManager, SecretCacheConfiguration config)`  
Constructs a new cache using a Secrets Manager client created using the provided [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) and a [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md). Use this constructor to customize the Secrets Manager client, for example to use a specific region or endpoint as well as configure the cache, for example the number of secrets to cache and how often it refreshes.  
**Parameters**    
secretsManager  
The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from.  
config  
A [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) that contains configuration information for the cache.

## Methods
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods"></a>

### GetSecretString
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretString"></a>

 `public async Task<String> GetSecretString(String secretId)`

Retrieves a string secret from Secrets Manager.Parameters

secretId  
The ARN or name of the secret to retrieve.

### GetSecretBinary
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretBinary"></a>

`public async Task<byte[]> GetSecretBinary(String secretId)`

Retrieves a binary secret from Secrets Manager.Parameters

secretId  
The ARN or name of the secret to retrieve.

### RefreshNowAsync
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-RefreshNowAsync"></a>

`public async Task<bool> RefreshNowAsync(String secretId)`

Requests the secret value from Secrets Manager and updates the cache with any changes. If there is no existing cache entry, creates a new one. Returns `true` if the refresh is successful.Parameters

secretId  
The ARN or name of the secret to retrieve.

### GetCachedSecret
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetCachedSecret"></a>

`public SecretCacheItem GetCachedSecret(string secretId)`

Returns the cache entry for the specified secret if it exists in the cache. Otherwise, retrieves the secret from Secrets Manager and creates a new cache entry.Parameters

secretId  
The ARN or name of the secret to retrieve.

# SecretCacheConfiguration
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration"></a>

Cache configuration options for a [SecretsManagerCache](retrieving-secrets_cache-net-SecretsManagerCache.md), such as maximum cache size and Time to Live (TTL) for cached secrets.

## Properties
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties"></a>

### CacheItemTTL
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheItemTTL"></a>

`public uint CacheItemTTL { get; set; }`

The TTL of a cache item in milliseconds. The default is `3600000` ms or 1 hour. The maximum is `4294967295` ms, which is approximately 49.7 days.

### MaxCacheSize
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_MaxCacheSize"></a>

`public ushort MaxCacheSize { get; set; }`

The maximum cache size. The default is 1024 secrets. The maximum is 65,535.

### VersionStage
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_VersionStage"></a>

`public string VersionStage { get; set; }`

The version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is `"AWSCURRENT"`.

### Client
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_Client"></a>

`public IAmazonSecretsManager Client { get; set; }`

The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from. If it is `null`, the cache instantiates a new client. The default is `null`.

### CacheHook
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheHook"></a>

`public ISecretCacheHook CacheHook { get; set; }`

A [ISecretCacheHook](retrieving-secrets_cache-net-ISecretCacheHook.md).

# ISecretCacheHook
<a name="retrieving-secrets_cache-net-ISecretCacheHook"></a>

An interface to hook into a [SecretsManagerCache](retrieving-secrets_cache-net-SecretsManagerCache.md) to perform actions on the secrets being stored in the cache. 

## Methods
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods"></a>

### Put
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods-Put"></a>

`object Put(object o);`

Prepare the object for storing in the cache.

Returns the object to store in the cache.

### Get
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods-Get"></a>

`object Get(object cachedObject);`

Derive the object from the cached object.

Returns the object to return from the cache