Skip to content

AspNet.Security.OAuth.Apple doesn't set cache entry's size #1190

@yasmoradi

Description

@yasmoradi

When configuring IMemoryCache in NET apps, it is a best practice to set a SizeLimit to prevent unbounded memory growth and reduce Garbage Collector (GC) pressure. High memory consumption without limits can lead to frequent Gen 2 collections, increasing latency and potentially causing OutOfMemoryException.

However, when a SizeLimit is defined on the cache, every cache entry must have a Size specified. Currently, the DefaultAppleClientSecretGenerator in AspNet.Security.OAuth.Apple generates and caches the client secret without setting the Size property. This causes issues in environments where cache size constraints are enforced.

Current Behavior

The DefaultAppleClientSecretGenerator uses GetOrCreateAsync without providing MemoryCacheEntryOptions that include a Size.

var clientSecret = await cache.GetOrCreateAsync(key, async (entry) =>
{
    try
    {
        (var clientSecret, entry.AbsoluteExpiration) = await GenerateNewSecretAsync(context);
        return clientSecret;
    }
    catch (Exception ex)
    {
        Log.ClientSecretGenerationFailed(logger, ex, context.Scheme.Name);
        throw;
    }
});

Proposed Changes

Specify a default Size (e.g., 1) for the cache entry to ensure compatibility with size-limited memory caches.

var clientSecret = await cache.GetOrCreateAsync(key, async (entry) =>
{
    try
    {
        (var clientSecret, entry.AbsoluteExpiration) = await GenerateNewSecretAsync(context);
        return clientSecret;
    }
    catch (Exception ex)
    {
        Log.ClientSecretGenerationFailed(logger, ex, context.Scheme.Name);
        throw;
    }
}, new MemoryCacheEntryOptions { Size = 1 });

Impact

This change ensures that users who configure services.AddMemoryCache(options => options.SizeLimit = ...) can use the Apple authentication provider without runtime errors related to missing cache entry sizes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions