| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.AspNetCore.DataProtection; |
| | | 3 | | |
| | | 4 | | namespace Elsa.SasTokens.Contracts; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A service that can create and decrypt SAS (Shared Access Signature) tokens using the <see cref="Microsoft.AspNetCore |
| | | 8 | | /// </summary> |
| | | 9 | | public class DataProtectorTokenService : ITokenService |
| | | 10 | | { |
| | | 11 | | private readonly IDataProtector _dataProtector; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Initializes a new instance of the <see cref="DataProtectorTokenService"/> class. |
| | | 15 | | /// </summary> |
| | 1 | 16 | | public DataProtectorTokenService(IDataProtectionProvider dataProtector) |
| | | 17 | | { |
| | 1 | 18 | | _dataProtector = dataProtector.CreateProtector("Elsa Tokens"); |
| | 1 | 19 | | } |
| | | 20 | | |
| | | 21 | | /// <inheritdoc /> |
| | | 22 | | public string CreateToken<T>(T payload, TimeSpan lifetime) |
| | | 23 | | { |
| | 0 | 24 | | var json = JsonSerializer.Serialize(payload); |
| | 0 | 25 | | return _dataProtector.ToTimeLimitedDataProtector().Protect(json, lifetime); |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <inheritdoc /> |
| | | 29 | | public string CreateToken<T>(T payload, DateTimeOffset expiresAt) |
| | | 30 | | { |
| | 0 | 31 | | var json = JsonSerializer.Serialize(payload); |
| | 0 | 32 | | return _dataProtector.ToTimeLimitedDataProtector().Protect(json, expiresAt); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public string CreateToken<T>(T payload) |
| | | 37 | | { |
| | 0 | 38 | | var json = JsonSerializer.Serialize(payload); |
| | 0 | 39 | | return _dataProtector.Protect(json); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <inheritdoc /> |
| | | 43 | | public bool TryDecryptToken<T>(string token, out T payload) |
| | | 44 | | { |
| | 0 | 45 | | payload = default!; |
| | | 46 | | |
| | | 47 | | try |
| | | 48 | | { |
| | 0 | 49 | | payload = DecryptToken<T>(token); |
| | 0 | 50 | | return true; |
| | | 51 | | } |
| | 0 | 52 | | catch |
| | | 53 | | { |
| | | 54 | | // ignored. |
| | 0 | 55 | | } |
| | | 56 | | |
| | 0 | 57 | | return false; |
| | 0 | 58 | | } |
| | | 59 | | |
| | | 60 | | /// <inheritdoc /> |
| | | 61 | | public T DecryptToken<T>(string token) |
| | | 62 | | { |
| | 0 | 63 | | var json = _dataProtector.Unprotect(token); |
| | 0 | 64 | | return JsonSerializer.Deserialize<T>(json)!; |
| | | 65 | | } |
| | | 66 | | } |