|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Concurrent; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Text.Json; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.AspNetCore.DataProtection; |
| 10 | +using Microsoft.JSInterop; |
| 11 | + |
| 12 | +namespace Microsoft.AspNetCore.Components.Web.Extensions |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Provides mechanisms for storing and retrieving data in the browser storage. |
| 16 | + /// </summary> |
| 17 | + public abstract class ProtectedBrowserStorage |
| 18 | + { |
| 19 | + private readonly string _storeName; |
| 20 | + private readonly IJSRuntime _jsRuntime; |
| 21 | + private readonly IDataProtectionProvider _dataProtectionProvider; |
| 22 | + private readonly ConcurrentDictionary<string, IDataProtector> _cachedDataProtectorsByPurpose |
| 23 | + = new ConcurrentDictionary<string, IDataProtector>(StringComparer.Ordinal); |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// Constructs an instance of <see cref="ProtectedBrowserStorage"/>. |
| 27 | + /// </summary> |
| 28 | + /// <param name="storeName">The name of the store in which the data should be stored.</param> |
| 29 | + /// <param name="jsRuntime">The <see cref="IJSRuntime"/>.</param> |
| 30 | + /// <param name="dataProtectionProvider">The <see cref="IDataProtectionProvider"/>.</param> |
| 31 | + protected ProtectedBrowserStorage(string storeName, IJSRuntime jsRuntime, IDataProtectionProvider dataProtectionProvider) |
| 32 | + { |
| 33 | + // Performing data protection on the client would give users a false sense of security, so we'll prevent this. |
| 34 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Browser)) |
| 35 | + { |
| 36 | + throw new PlatformNotSupportedException($"{GetType()} cannot be used when running in a browser."); |
| 37 | + } |
| 38 | + |
| 39 | + if (string.IsNullOrEmpty(storeName)) |
| 40 | + { |
| 41 | + throw new ArgumentException("The value cannot be null or empty", nameof(storeName)); |
| 42 | + } |
| 43 | + |
| 44 | + _storeName = storeName; |
| 45 | + _jsRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime)); |
| 46 | + _dataProtectionProvider = dataProtectionProvider ?? throw new ArgumentNullException(nameof(dataProtectionProvider)); |
| 47 | + } |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// <para> |
| 51 | + /// Asynchronously stores the specified data. |
| 52 | + /// </para> |
| 53 | + /// <para> |
| 54 | + /// Since no data protection purpose is specified with this overload, the purpose is derived from |
| 55 | + /// <paramref name="key"/> and the store name. This is a good default purpose to use if the keys come from a |
| 56 | + /// fixed set known at compile-time. |
| 57 | + /// </para> |
| 58 | + /// </summary> |
| 59 | + /// <param name="key">A <see cref="string"/> value specifying the name of the storage slot to use.</param> |
| 60 | + /// <param name="value">A JSON-serializable value to be stored.</param> |
| 61 | + /// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns> |
| 62 | + public ValueTask SetAsync(string key, object value) |
| 63 | + => SetAsync(CreatePurposeFromKey(key), key, value); |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Asynchronously stores the supplied data. |
| 67 | + /// </summary> |
| 68 | + /// <param name="purpose"> |
| 69 | + /// A string that defines a scope for the data protection. The protected data can only |
| 70 | + /// be unprotected by code that specifies the same purpose. |
| 71 | + /// </param> |
| 72 | + /// <param name="key">A <see cref="string"/> value specifying the name of the storage slot to use.</param> |
| 73 | + /// <param name="value">A JSON-serializable value to be stored.</param> |
| 74 | + /// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns> |
| 75 | + public ValueTask SetAsync(string purpose, string key, object value) |
| 76 | + { |
| 77 | + if (string.IsNullOrEmpty(purpose)) |
| 78 | + { |
| 79 | + throw new ArgumentException("Cannot be null or empty", nameof(purpose)); |
| 80 | + } |
| 81 | + |
| 82 | + if (string.IsNullOrEmpty(key)) |
| 83 | + { |
| 84 | + throw new ArgumentException("Cannot be null or empty", nameof(key)); |
| 85 | + } |
| 86 | + |
| 87 | + return SetProtectedJsonAsync(key, Protect(purpose, value)); |
| 88 | + } |
| 89 | + |
| 90 | + /// <summary> |
| 91 | + /// <para> |
| 92 | + /// Asynchronously retrieves the specified data. |
| 93 | + /// </para> |
| 94 | + /// <para> |
| 95 | + /// Since no data protection purpose is specified with this overload, the purpose is derived from |
| 96 | + /// <paramref name="key"/> and the store name. This is a good default purpose to use if the keys come from a |
| 97 | + /// fixed set known at compile-time. |
| 98 | + /// </para> |
| 99 | + /// </summary> |
| 100 | + /// <param name="key">A <see cref="string"/> value specifying the name of the storage slot to use.</param> |
| 101 | + /// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns> |
| 102 | + public ValueTask<ProtectedBrowserStorageResult<TValue>> GetAsync<TValue>(string key) |
| 103 | + => GetAsync<TValue>(CreatePurposeFromKey(key), key); |
| 104 | + |
| 105 | + /// <summary> |
| 106 | + /// <para> |
| 107 | + /// Asynchronously retrieves the specified data. |
| 108 | + /// </para> |
| 109 | + /// </summary> |
| 110 | + /// <param name="purpose"> |
| 111 | + /// A string that defines a scope for the data protection. The protected data can only |
| 112 | + /// be unprotected if the same purpose was previously specified when calling |
| 113 | + /// <see cref="SetAsync(string, string, object)"/>. |
| 114 | + /// </param> |
| 115 | + /// <param name="key">A <see cref="string"/> value specifying the name of the storage slot to use.</param> |
| 116 | + /// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns> |
| 117 | + public async ValueTask<ProtectedBrowserStorageResult<TValue>> GetAsync<TValue>(string purpose, string key) |
| 118 | + { |
| 119 | + var protectedJson = await GetProtectedJsonAsync(key); |
| 120 | + |
| 121 | + return protectedJson == null ? |
| 122 | + new ProtectedBrowserStorageResult<TValue>(false, default) : |
| 123 | + new ProtectedBrowserStorageResult<TValue>(true, Unprotect<TValue>(purpose, protectedJson)); |
| 124 | + } |
| 125 | + |
| 126 | + /// <summary> |
| 127 | + /// Asynchronously deletes any data stored for the specified key. |
| 128 | + /// </summary> |
| 129 | + /// <param name="key"> |
| 130 | + /// A <see cref="string"/> value specifying the name of the storage slot whose value should be deleted. |
| 131 | + /// </param> |
| 132 | + /// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns> |
| 133 | + public ValueTask DeleteAsync(string key) |
| 134 | + => _jsRuntime.InvokeVoidAsync($"{_storeName}.removeItem", key); |
| 135 | + |
| 136 | + private string Protect(string purpose, object value) |
| 137 | + { |
| 138 | + var json = JsonSerializer.Serialize(value, options: JsonSerializerOptionsProvider.Options); |
| 139 | + var protector = GetOrCreateCachedProtector(purpose); |
| 140 | + |
| 141 | + return protector.Protect(json); |
| 142 | + } |
| 143 | + |
| 144 | + private TValue Unprotect<TValue>(string purpose, string protectedJson) |
| 145 | + { |
| 146 | + var protector = GetOrCreateCachedProtector(purpose); |
| 147 | + var json = protector.Unprotect(protectedJson); |
| 148 | + |
| 149 | + return JsonSerializer.Deserialize<TValue>(json, options: JsonSerializerOptionsProvider.Options)!; |
| 150 | + } |
| 151 | + |
| 152 | + private ValueTask SetProtectedJsonAsync(string key, string protectedJson) |
| 153 | + => _jsRuntime.InvokeVoidAsync($"{_storeName}.setItem", key, protectedJson); |
| 154 | + |
| 155 | + private ValueTask<string> GetProtectedJsonAsync(string key) |
| 156 | + => _jsRuntime.InvokeAsync<string>($"{_storeName}.getItem", key); |
| 157 | + |
| 158 | + // IDataProtect isn't disposable, so we're fine holding these indefinitely. |
| 159 | + // Only a bounded number of them will be created, as the 'key' values should |
| 160 | + // come from a bounded set known at compile-time. There's no use case for |
| 161 | + // letting runtime data determine the 'key' values. |
| 162 | + private IDataProtector GetOrCreateCachedProtector(string purpose) |
| 163 | + => _cachedDataProtectorsByPurpose.GetOrAdd( |
| 164 | + purpose, |
| 165 | + _dataProtectionProvider.CreateProtector); |
| 166 | + |
| 167 | + private string CreatePurposeFromKey(string key) |
| 168 | + => $"{GetType().FullName}:{_storeName}:{key}"; |
| 169 | + } |
| 170 | +} |
0 commit comments