1
0
mirror of https://github.com/bitwarden/server synced 2026-01-03 17:14:00 +00:00

Feature/token service (#1785)

* Implement draft token service

* Add tokenizer and factory

* Handle expiring tokens through base class

* Allow direct token validity checks

* Add safe unprotect to tokenizer

* Add interface to tokenizer factory

* Use tokenizer

* Fix rebase

* Handle cleartext prefix in tokenizer base

* Use epoch milliseconds for expiration in tokens

* Use tokenizers

* Test tokens

* Linter fixes

* Add TokenizerFactory to DI services

* Test epoch milliseconds deserialization

* Use separate injectables for each token type

* Fix directory

* Add functional unprotect to token

* Fix namespace and correct object names

* Remove Tokenable interface

* Test remaining Tokens classes

* Dotnet format

* Fix sut provider errors with update

* Remove useless property

Co-authored-by: Hinton <oscar@oscarhinton.com>
This commit is contained in:
Matt Gibson
2022-01-10 10:58:16 -05:00
committed by GitHub
parent 924ebca153
commit e2c6fc81f4
19 changed files with 562 additions and 33 deletions

View File

@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.DataProtection;
namespace Bit.Core.Tokens
{
public class DataProtectorTokenFactory<T> : IDataProtectorTokenFactory<T> where T : Tokenable
{
private readonly IDataProtector _dataProtector;
private readonly string _clearTextPrefix;
public DataProtectorTokenFactory(string clearTextPrefix, string purpose, IDataProtectionProvider dataProtectionProvider)
{
_dataProtector = dataProtectionProvider.CreateProtector(purpose);
_clearTextPrefix = clearTextPrefix;
}
public string Protect(T data) =>
data.ToToken().ProtectWith(_dataProtector).WithPrefix(_clearTextPrefix).ToString();
public T Unprotect(string token) =>
Tokenable.FromToken<T>(new Token(token).RemovePrefix(_clearTextPrefix).UnprotectWith(_dataProtector).ToString());
public bool TokenValid(string token)
{
try
{
return Unprotect(token).Valid;
}
catch
{
return false;
}
}
public bool TryUnprotect(string token, out T data)
{
try
{
data = Unprotect(token);
return true;
}
catch
{
data = default;
return false;
}
}
}
}