mirror of
https://github.com/bitwarden/server.git
synced 2025-01-09 19:57:37 +01:00
c8c9b32904
* Add logging to token usages * Add settings manipulation of log levels * Maintain no logging for dev * Log exception causing Token failure in TryUnprotect * dotnet format 🤖 * Added deconstruction operator on new debug logs. * Split off log level settings into separate files * Improve log messages * dotnet format 🤖 * Fix token serialization * Final review notes Co-authored-by: Todd Martin <>
55 lines
1.3 KiB
C#
55 lines
1.3 KiB
C#
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Bit.Core.Tokens;
|
|
|
|
public class Token
|
|
{
|
|
private readonly string _token;
|
|
|
|
public Token(string token)
|
|
{
|
|
_token = token;
|
|
}
|
|
|
|
public Token WithPrefix(string prefix)
|
|
{
|
|
return new Token($"{prefix}{_token}");
|
|
}
|
|
|
|
public Token RemovePrefix(string expectedPrefix)
|
|
{
|
|
if (!_token.StartsWith(expectedPrefix))
|
|
{
|
|
throw new BadTokenException($"Expected prefix, {expectedPrefix}, was not present.");
|
|
}
|
|
|
|
return new Token(_token[expectedPrefix.Length..]);
|
|
}
|
|
|
|
|
|
public Token ProtectWith(IDataProtector dataProtector, ILogger logger)
|
|
{
|
|
logger.LogDebug("Protecting token: {token}", this);
|
|
return new(dataProtector.Protect(ToString()));
|
|
}
|
|
|
|
public Token UnprotectWith(IDataProtector dataProtector, ILogger logger)
|
|
{
|
|
var unprotected = "";
|
|
try
|
|
{
|
|
unprotected = dataProtector.Unprotect(ToString());
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
logger.LogInformation(e, "Failed to unprotect token: {token}", this);
|
|
throw;
|
|
}
|
|
logger.LogDebug("Unprotected token: {token} to {decryptedToken}", this, unprotected);
|
|
return new(unprotected);
|
|
}
|
|
|
|
public override string ToString() => _token;
|
|
}
|