diff --git a/src/Blazor.Caching/CacheStorageAccessor.cs b/src/Blazor.Caching/CacheStorageAccessor.cs new file mode 100644 index 00000000..f0f2ab7f --- /dev/null +++ b/src/Blazor.Caching/CacheStorageAccessor.cs @@ -0,0 +1,98 @@ +namespace Dgmjr.Blazor.Caching; + +public class CacheStorageAccessor : IAsyncDisposable +{ + private Lazy _accessorJsRef = new(); + private readonly IJSRuntime _jsRuntime; + + public CacheStorageAccessor(IJSRuntime jsRuntime) + { + _jsRuntime = jsRuntime; + } + + private async Task WaitForReference() + { + if (_accessorJsRef.IsValueCreated is false) + { + _accessorJsRef = new( + await _jsRuntime.InvokeAsync( + "import", + "/js/CacheStorageAccessor.js" + ) + ); + } + } + + public async ValueTask DisposeAsync() + { + if (_accessorJsRef.IsValueCreated) + { + await _accessorJsRef.Value.DisposeAsync(); + } + } + + public async Task StoreAsync( + HttpRequestMessage requestMessage, + HttpResponseMessage responseMessage + ) + { + await WaitForReference(); + string requestMethod = requestMessage.Method.Method; + string requestBody = await GetRequestBodyAsync(requestMessage); + string responseBody = await responseMessage.Content.ReadAsStringAsync(); + + await _accessorJsRef.Value.InvokeVoidAsync( + "store", + requestMessage.RequestUri, + requestMethod, + requestBody, + responseBody + ); + } + + public async Task GetAsync(HttpRequestMessage requestMessage) + { + await WaitForReference(); + string requestMethod = requestMessage.Method.Method; + string requestBody = await GetRequestBodyAsync(requestMessage); + string result = await _accessorJsRef.Value.InvokeAsync( + "get", + requestMessage.RequestUri, + requestMethod, + requestBody + ); + + return result; + } + + public async Task RemoveAsync(HttpRequestMessage requestMessage) + { + await WaitForReference(); + string requestMethod = requestMessage.Method.Method; + string requestBody = await GetRequestBodyAsync(requestMessage); + await _accessorJsRef.Value.InvokeVoidAsync( + "remove", + requestMessage.RequestUri, + requestMethod, + requestBody + ); + } + + public async Task RemoveAllAsync() + { + await WaitForReference(); + await _accessorJsRef.Value.InvokeVoidAsync("removeAll"); + } + + private static async Task GetRequestBodyAsync(HttpRequestMessage requestMessage) + { + string requestBody = ""; + + if (requestMessage.Content is not null) + { + requestBody = await requestMessage.Content.ReadAsStringAsync() ?? ""; + } + + return requestBody; + } +} diff --git a/src/Blazor.Caching/Dgmjr.Blazor.Caching.csproj b/src/Blazor.Caching/Dgmjr.Blazor.Caching.csproj new file mode 100644 index 00000000..d213a127 --- /dev/null +++ b/src/Blazor.Caching/Dgmjr.Blazor.Caching.csproj @@ -0,0 +1,8 @@ + + + net6.0;net8.0 + + + + + diff --git a/src/Blazor.Security/Constants/BlazorSecurityConstants.cs b/src/Blazor.Security/Constants/BlazorSecurityConstants.cs new file mode 100644 index 00000000..66c1974d --- /dev/null +++ b/src/Blazor.Security/Constants/BlazorSecurityConstants.cs @@ -0,0 +1,6 @@ +namespace Dgmjr.Blazor.Security; + +public static class BlazorSecurityConstants +{ + public const string BlazorSecurity = nameof(BlazorSecurity); +} diff --git a/src/Blazor.Security/Controllers/AccountController.cs b/src/Blazor.Security/Controllers/AccountController.cs new file mode 100644 index 00000000..4b5e9493 --- /dev/null +++ b/src/Blazor.Security/Controllers/AccountController.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Mvc; +using Dgmjr.Blazor.Security.Models; +using Microsoft.Extensions.Logging; +using Dgmjr.AspNetCore.Mvc; + +namespace Dgmjr.Blazor.Security.Controllers; + +[Route("Account/[action]")] +[ApiController] +public partial class AccountController(ILogger logger) : ApiControllerBase(logger) +{ + public IActionResult Login(string redirectUri) + { + var redirectUrl = redirectUri ?? Url.Content("~/"); + + return Challenge( + new AuthenticationProperties { RedirectUri = redirectUrl }, + OpenIdConnectDefaults.AuthenticationScheme + ); + } + + public IActionResult Logout() + { + var redirectUrl = Url.Content("~/"); + + return SignOut( + new AuthenticationProperties { RedirectUri = redirectUrl }, + CookieAuthenticationDefaults.AuthenticationScheme, + OpenIdConnectDefaults.AuthenticationScheme + ); + } + + [HttpPost] + public ApplicationAuthenticationState CurrentUser() + { + return new ApplicationAuthenticationState + { + IsAuthenticated = User.Identities.Any(id => id.IsAuthenticated), + Name = User.Identity.Name, + Claims = User.Claims.Select( + c => new ApplicationClaim { Type = c.Type, Value = c.Value } + ) + }; + } +} diff --git a/src/Blazor.Security/Dgmjr.Blazor.Security.csproj b/src/Blazor.Security/Dgmjr.Blazor.Security.csproj new file mode 100644 index 00000000..a3c25ff0 --- /dev/null +++ b/src/Blazor.Security/Dgmjr.Blazor.Security.csproj @@ -0,0 +1,13 @@ + + + net8.0 + + + + + + + + + + diff --git a/src/Blazor.Security/LICENSE.md b/src/Blazor.Security/LICENSE.md new file mode 100644 index 00000000..4f592f86 --- /dev/null +++ b/src/Blazor.Security/LICENSE.md @@ -0,0 +1,35 @@ +--- +date: 2023-07-13T05:44:46:00-05:00Z +description: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files, yadda, yadda, yadda... +keywords: +- IP +- copyright +- license +- mit +permissions: +- commercial-use +- modifications +- distribution +- private-use +conditions: +- include-copyright +limitations: +- liability +- warranty +lastmod: 2024-01-0T00:39:00.0000+05:00Z +license: MIT +slug: mit-license +title: MIT License +type: license +--- + +# MIT License + +## Copyright © 2022-2024 [David G. Moore, Jr.](mailto:david@dgmjr.io "Send Dr. Moore") ([@dgmjr](https://github.com/dgmjr "Contact Dr. Moore on GitHub")), All Rights Reserved + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/src/Blazor.Security/Models/ApplicationAuthenticationState.cs b/src/Blazor.Security/Models/ApplicationAuthenticationState.cs new file mode 100644 index 00000000..fa7a35ef --- /dev/null +++ b/src/Blazor.Security/Models/ApplicationAuthenticationState.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace Dgmjr.Blazor.Security.Models; + +public partial class ApplicationAuthenticationState +{ + public bool IsAuthenticated { get; set; } + public string Name { get; set; } + public IEnumerable Claims { get; set; } +} diff --git a/src/Blazor.Security/Models/ApplicationClaim.cs b/src/Blazor.Security/Models/ApplicationClaim.cs new file mode 100644 index 00000000..0e30c3aa --- /dev/null +++ b/src/Blazor.Security/Models/ApplicationClaim.cs @@ -0,0 +1,7 @@ +namespace Dgmjr.Blazor.Security.Models; + +public class ApplicationClaim +{ + public string Type { get; set; } + public string Value { get; set; } +} diff --git a/src/Blazor.Security/Models/ApplicationUser.cs b/src/Blazor.Security/Models/ApplicationUser.cs new file mode 100644 index 00000000..1635533a --- /dev/null +++ b/src/Blazor.Security/Models/ApplicationUser.cs @@ -0,0 +1,9 @@ +using System; +using System.Collections.Generic; + +namespace Dgmjr.Blazor.Security.Models; + +public partial class ApplicationUser +{ + public string Name { get; set; } +} diff --git a/src/Blazor.Security/SecurityServiceCollectionExtensions.cs b/src/Blazor.Security/SecurityServiceCollectionExtensions.cs new file mode 100644 index 00000000..5c64226a --- /dev/null +++ b/src/Blazor.Security/SecurityServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +using Dgmjr.Blazor.Security.Services; + +namespace Microsoft.Extensions.DependencyInjection; + +public static class SecurityServiceCollectionExtensions +{ + public static IServiceCollection AddSecurityService(this IServiceCollection services) + { + services.AddScoped(); + return services; + } +} diff --git a/src/Blazor.Security/Services/ApplicationAuthenticationStateProvider.cs b/src/Blazor.Security/Services/ApplicationAuthenticationStateProvider.cs new file mode 100644 index 00000000..9b80fb58 --- /dev/null +++ b/src/Blazor.Security/Services/ApplicationAuthenticationStateProvider.cs @@ -0,0 +1,46 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Components.Authorization; + +using Dgmjr.Blazor.Security.Models; + +namespace Dgmjr.Blazor.Security.Services; + +public class ApplicationAuthenticationStateProvider(ISecurityService securityService) : AuthenticationStateProvider +{ + private ApplicationAuthenticationState _authenticationState; + + public override async Task GetAuthenticationStateAsync() + { + var identity = new ClaimsIdentity(); + + try + { + var state = await GetApplicationAuthenticationStateAsync(); + + if (state.IsAuthenticated) + { + identity = new ClaimsIdentity( + state.Claims.Select(c => new Claim(c.Type, c.Value)), + BlazorSecurityConstants.BlazorSecurity + ); + } + } + catch (HttpRequestException) { /* swallow the exception */ } + + var result = new AuthenticationState(new ClaimsPrincipal(identity)); + + securityService.Initialize(result); + + return result; + } + + private async Task GetApplicationAuthenticationStateAsync() + { + return _authenticationState ??= await securityService.GetAuthenticationStateAsync(); + } +} diff --git a/src/Blazor.Security/Services/ISecurityService.cs b/src/Blazor.Security/Services/ISecurityService.cs new file mode 100644 index 00000000..d443e220 --- /dev/null +++ b/src/Blazor.Security/Services/ISecurityService.cs @@ -0,0 +1,20 @@ +using System.Security.Claims; + +using Dgmjr.Blazor.Security.Models; + +using Microsoft.AspNetCore.Components.Authorization; + +namespace Dgmjr.Blazor.Security.Services; + +public interface ISecurityService +{ + ApplicationUser User { get; } + ClaimsPrincipal Principal { get; } + + Task GetAuthenticationStateAsync(); + bool Initialize(AuthenticationState result); + bool IsAuthenticated(); + bool IsInRole(params string[] roles); + void Login(); + void Logout(); +} diff --git a/src/Blazor.Security/Services/SecurityService.cs b/src/Blazor.Security/Services/SecurityService.cs new file mode 100644 index 00000000..0bd7854a --- /dev/null +++ b/src/Blazor.Security/Services/SecurityService.cs @@ -0,0 +1,84 @@ +using System; +using System.Web; +using System.Linq; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using System.Text; +using System.Text.Json; +using System.Security.Claims; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; + +using Radzen; + +using Dgmjr.Blazor.Security.Models; + +namespace Dgmjr.Blazor.Security.Services; + +public partial class SecurityService(NavigationManager navigationManager, IHttpClientFactory factory) : ISecurityService +{ + private readonly HttpClient _httpClient = factory.CreateClient(BlazorSecurityConstants.BlazorSecurity); + + public ApplicationUser User { get; private set; } = new ApplicationUser { Name = "Anonymous" }; + + public ClaimsPrincipal Principal { get; private set; } + + public async Task GetAuthenticationStateAsync() + { + var uri = new Uri($"{navigationManager.BaseUri}Account/CurrentUser"); + + var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, uri)); + + return await response.ReadAsync(); + } + + public bool IsInRole(params string[] roles) + { + if (roles.Contains("Everybody")) + { + return true; + } + + if (!IsAuthenticated()) + { + return false; + } + + if (roles.Contains("Authenticated")) + { + return true; + } + + return roles.Any(role => Principal.IsInRole(role)); + } + + public bool IsAuthenticated() + { + return Principal?.Identity.IsAuthenticated == true; + } + + public bool Initialize(AuthenticationState result) + { + Principal = result.User; + + var name = Principal.FindFirstValue(ClaimTypes.Name) ?? Principal.FindFirstValue("name"); + + if (name != null) + { + User = new ApplicationUser { Name = name }; + } + + return IsAuthenticated(); + } + + public void Logout() + { + navigationManager.NavigateTo("Account/Logout", true); + } + + public void Login() + { + navigationManager.NavigateTo("Login", true); + } +} diff --git a/src/Blazor.Security/icon.png b/src/Blazor.Security/icon.png new file mode 100644 index 00000000..db07a039 Binary files /dev/null and b/src/Blazor.Security/icon.png differ diff --git a/src/Configuration/DependencyInjection/KeyPerJsonFileConfigurationExtensions.cs b/src/Configuration/DependencyInjection/KeyPerJsonFileConfigurationExtensions.cs index c3341566..6886efdd 100644 --- a/src/Configuration/DependencyInjection/KeyPerJsonFileConfigurationExtensions.cs +++ b/src/Configuration/DependencyInjection/KeyPerJsonFileConfigurationExtensions.cs @@ -1,6 +1,8 @@ namespace Microsoft.Extensions.DependencyInjection; -using Dgmjr.Configuration.Extensions; +using System.Collections; +using System.Collections.Generic; +using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; @@ -9,10 +11,10 @@ namespace Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; -using System.Collections; -using System.Collections.Generic; -using System.IO; +using Dgmjr.Configuration.Extensions; + using static KeyPerJsonFileConfigurationExtensions; +using System.CodeDom.Compiler; internal static partial class KeyPerJsonFileConfigurationExtensions { @@ -144,11 +146,12 @@ public static string MakeAppsettingsJsonFile(this DirectoryInfo directory, bool var jsonBuilder = new StringBuilder(); using (var appsettingsJsonFile = File.CreateText(appsettingsJsonFileName)) using (var jsonWriter = new StringWriter(jsonBuilder)) - using (var multiWriter = new MultiWriter(appsettingsJsonFile, jsonWriter)) + using (var multiWriter = new IndentedTextWriter(new MultiWriter(appsettingsJsonFile, jsonWriter))) { var jsonFiles = directory.GetJsonFiles(recursive); - appsettingsJsonFile.WriteLine("{"); + multiWriter.WriteLine("{"); + multiWriter.IncreaseIndent(); foreach (var jsonFile in jsonFiles) { @@ -162,6 +165,7 @@ public static string MakeAppsettingsJsonFile(this DirectoryInfo directory, bool multiWriter.WriteLine(File.ReadAllText(jsonFile.FullName)); multiWriter.WriteLine(","); } + multiWriter.DecreaseIndent(); multiWriter.WriteLine("}"); } diff --git a/src/Configuration/Extensions/IndentedTextWriterExtensions.cs b/src/Configuration/Extensions/IndentedTextWriterExtensions.cs new file mode 100644 index 00000000..7f2d9c6c --- /dev/null +++ b/src/Configuration/Extensions/IndentedTextWriterExtensions.cs @@ -0,0 +1,14 @@ +namespace Dgmjr.Configuration.Extensions; + +public static class IndentedTextWriterExtensions +{ + public static void IncreaseIndent(this IndentedTextWriter writer) + { + writer.Indent += 2; + } + + public static void DecreaseIndent(this IndentedTextWriter writer) + { + writer.Indent -= 2; + } +}