The core infrastructure backend (API, database, Docker, etc).
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

71 lines
2.3 KiB

// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using System.Text;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Core.Auth.IdentityServer;
public class DistributedCacheCookieManager : ICookieManager
{
private readonly ChunkingCookieManager _cookieManager;
public DistributedCacheCookieManager()
{
_cookieManager = new ChunkingCookieManager();
}
private string CacheKeyPrefix => "cookie-data";
public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{
var id = Guid.NewGuid().ToString();
var cacheKey = GetKey(key, id);
var expiresUtc = options.Expires ?? DateTimeOffset.UtcNow.AddMinutes(15);
var cacheOptions = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(expiresUtc);
var data = Encoding.UTF8.GetBytes(value);
var cache = GetCache(context);
cache.Set(cacheKey, data, cacheOptions);
// Write the cookie with the identifier as the body
_cookieManager.AppendResponseCookie(context, key, id, options);
}
public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
_cookieManager.DeleteCookie(context, key, options);
var id = GetId(context, key);
if (!string.IsNullOrWhiteSpace(id))
{
var cacheKey = GetKey(key, id);
GetCache(context).Remove(cacheKey);
}
}
public string GetRequestCookie(HttpContext context, string key)
{
var id = GetId(context, key);
if (string.IsNullOrWhiteSpace(id))
{
return null;
}
var cacheKey = GetKey(key, id);
return GetCache(context).GetString(cacheKey);
}
private IDistributedCache GetCache(HttpContext context) =>
context.RequestServices.GetRequiredKeyedService<IDistributedCache>("persistent");
private string GetKey(string key, string id) => $"{CacheKeyPrefix}-{key}-{id}";
private string GetId(HttpContext context, string key) =>
context.Request.Cookies.TryGetValue(key, out var cookie) ?
cookie : null;
}