1
0
mirror of https://github.com/bitwarden/server synced 2025-12-26 05:03:18 +00:00
Files
server/src/Core/Auth/IdentityServer/DistributedCacheTicketDataFormatter.cs
Ike 96fe09af89 [PM-25415] move files into better place for code ownership (#6275)
* chore: move files into better place for code ownership

* fix: import correct namespace
2025-09-04 10:08:03 -04:00

68 lines
2.2 KiB
C#

// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Caching.Distributed;
namespace Bit.Core.Auth.IdentityServer;
public class DistributedCacheTicketDataFormatter : ISecureDataFormat<AuthenticationTicket>
{
private const string CacheKeyPrefix = "ticket-data";
private readonly IDistributedCache _distributedCache;
private readonly IDataProtector _dataProtector;
private readonly string _prefix;
public DistributedCacheTicketDataFormatter(
IDistributedCache distributedCache,
IDataProtectionProvider dataProtectionProvider,
string name)
{
_distributedCache = distributedCache;
_dataProtector = dataProtectionProvider.CreateProtector(CacheKeyPrefix, name);
_prefix = $"{CacheKeyPrefix}-{name}";
}
public string Protect(AuthenticationTicket data) => Protect(data, null);
public string Protect(AuthenticationTicket data, string purpose)
{
var key = Guid.NewGuid().ToString();
var cacheKey = $"{_prefix}-{purpose}-{key}";
var expiresUtc = data.Properties.ExpiresUtc ??
DateTimeOffset.UtcNow.AddMinutes(15);
var options = new DistributedCacheEntryOptions();
options.SetAbsoluteExpiration(expiresUtc);
var ticket = TicketSerializer.Default.Serialize(data);
_distributedCache.Set(cacheKey, ticket, options);
return _dataProtector.Protect(key);
}
public AuthenticationTicket Unprotect(string protectedText) => Unprotect(protectedText, null);
public AuthenticationTicket Unprotect(string protectedText, string purpose)
{
if (string.IsNullOrWhiteSpace(protectedText))
{
return null;
}
// Decrypt the key and retrieve the data from the cache.
var key = _dataProtector.Unprotect(protectedText);
var cacheKey = $"{_prefix}-{purpose}-{key}";
var ticket = _distributedCache.Get(cacheKey);
if (ticket == null)
{
return null;
}
var data = TicketSerializer.Default.Deserialize(ticket);
return data;
}
}