From 794f584d9f858a62977dadece719c45f458ee0bb Mon Sep 17 00:00:00 2001 From: sakecrystal Date: Thu, 29 Oct 2026 11:26:16 +0900 Subject: [PATCH] Harden CoreAdmin authorization and antiforgery protection --- README.md | 17 +- .../Program.cs | 8 +- .../Controllers/CoreAdminDataController.cs | 4 +- src/DotNetEd.CoreAdmin/CoreAdminAuthFilter.cs | 12 +- .../CoreAdminSecurityOptions.cs | 6 + .../Views/CoreAdminData/Create.cshtml | 2 +- .../Views/CoreAdminData/DeleteEntity.cshtml | 2 +- .../Views/CoreAdminData/Edit.cshtml | 2 +- .../BasicTests.cs | 10 +- .../CrudTests.cs | 156 +++++++++++++++++- .../OptionsTests.cs | 16 +- .../SecurityTests.cs | 67 +++++++- 12 files changed, 271 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 0666fad..7d58b6d 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ dotnet add package CoreAdmin Add this line before ```var app = builder.Build();``` and after your DbContexts have been added to Services in Program.cs: ```csharp -builder.Services.AddCoreAdmin(); +builder.Services.AddCoreAdmin("Administrator"); ``` You need to make sure Endpoints are enabled as they don't appear to be in the default templates. @@ -57,7 +57,7 @@ dotnet add package CoreAdmin Add this line at the bottom of ConfigureServices() (and after your DbContexts have been added to Services) in Startup.cs: ```csharp -services.AddCoreAdmin(); +services.AddCoreAdmin("Administrator"); ``` ## Running the app @@ -65,7 +65,18 @@ Run your app with with /coreadmin on the end of the URL, for example https://loc ### Security -Basic role based security is currently supported. Whilst this does not need to be set up when running the admin panel in Development mode (for testing), all other environments need this set up. +Core Admin denies access by default unless a role restriction or custom authorization method is configured. This applies in Development as well as Production. + +For an intentionally unprotected local demo or test only, you can explicitly enable the Development-only bypass. This setting has no effect outside Development and should not be enabled in production or on a network-accessible development server: + +```csharp +builder.Services.AddCoreAdmin(new DotNetEd.CoreAdmin.CoreAdminOptions +{ + AllowUnauthenticatedAccessInDevelopment = true +}); +``` + +For real applications, configure a role restriction or a custom authorization method instead. #### Role based security diff --git a/src/DotNetEd.CoreAdmin.DemoAppDotNet10/Program.cs b/src/DotNetEd.CoreAdmin.DemoAppDotNet10/Program.cs index 40c7000..2d70c4d 100644 --- a/src/DotNetEd.CoreAdmin.DemoAppDotNet10/Program.cs +++ b/src/DotNetEd.CoreAdmin.DemoAppDotNet10/Program.cs @@ -1,3 +1,4 @@ +using DotNetEd.CoreAdmin; using DotNetEd.CoreAdmin.DemoApp.Models; using Microsoft.EntityFrameworkCore; @@ -10,7 +11,12 @@ builder.Services.AddDbContext(options => options.UseInMemoryDatabase("TestDatabase")); // add Core Admin -builder.Services.AddCoreAdmin(); +// Demo-only opt-in. This bypass is effective only in Development. +// Real applications should configure a role restriction or custom authorization. +builder.Services.AddCoreAdmin(new CoreAdminOptions +{ + AllowUnauthenticatedAccessInDevelopment = builder.Environment.IsDevelopment() +}); var app = builder.Build(); diff --git a/src/DotNetEd.CoreAdmin/Controllers/CoreAdminDataController.cs b/src/DotNetEd.CoreAdmin/Controllers/CoreAdminDataController.cs index f2572f3..e2b0f97 100644 --- a/src/DotNetEd.CoreAdmin/Controllers/CoreAdminDataController.cs +++ b/src/DotNetEd.CoreAdmin/Controllers/CoreAdminDataController.cs @@ -13,6 +13,7 @@ namespace DotNetEd.CoreAdmin.Controllers { [CoreAdminAuth] + [AutoValidateAntiforgeryToken] public class CoreAdminDataController : Controller { private readonly IEnumerable dbSetEntities; @@ -161,7 +162,6 @@ private object GetEntityFromDbSet(string dbSetName, string id, } [HttpPost] - [IgnoreAntiforgeryToken] public async Task CreateEntityPost(string dbSetName, string id, [FromForm] object formData) { var dbSetValue = GetDbSetValueOrNull(dbSetName, out var dbContextObject, out var entityType, out var relationships); @@ -207,7 +207,6 @@ await CompositeValueProvider.CreateAsync(this.ControllerContext, this.Controller } [HttpGet] - [IgnoreAntiforgeryToken] public IActionResult Create(string id) { var dbSetValue = GetDbSetValueOrNull(id, out var dbContextObject, out var entityType, out var relationships); @@ -311,7 +310,6 @@ public IActionResult DeleteEntity(string dbSetName, string id) } [HttpPost] - [IgnoreAntiforgeryToken] public async Task DeleteEntityPost([FromForm] DataDeleteViewModel viewModel) { foreach (var dbSetEntity in dbSetEntities.Where(db => db.Name.ToLowerInvariant() == viewModel.DbSetName.ToLowerInvariant())) diff --git a/src/DotNetEd.CoreAdmin/CoreAdminAuthFilter.cs b/src/DotNetEd.CoreAdmin/CoreAdminAuthFilter.cs index cf64e8d..3179ead 100644 --- a/src/DotNetEd.CoreAdmin/CoreAdminAuthFilter.cs +++ b/src/DotNetEd.CoreAdmin/CoreAdminAuthFilter.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace DotNetEd.CoreAdmin @@ -12,7 +13,7 @@ public class CoreAdminAuthAttribute : TypeFilterAttribute public CoreAdminAuthAttribute() : base(typeof(CoreAdminAuthFilter)) { } } - public class CoreAdminAuthFilter : IAuthorizationFilter + public class CoreAdminAuthFilter : IAsyncAuthorizationFilter { private readonly IWebHostEnvironment environment; private readonly IList coreAdminOptions; @@ -25,13 +26,16 @@ public CoreAdminAuthFilter(IWebHostEnvironment environment, IEnumerable o.IsSecuritySet)) + // Permit the Development-only bypass only when explicitly opted in. + // Missing security configuration is denied by default in every environment. + if (environment.EnvironmentName == "Development" + && coreAdminOptions.Any(o => o.AllowUnauthenticatedAccessInDevelopment) + && !coreAdminOptions.Any(o => o.IsSecuritySet)) { failedSecurityCheck = false; } diff --git a/src/DotNetEd.CoreAdmin/CoreAdminSecurityOptions.cs b/src/DotNetEd.CoreAdmin/CoreAdminSecurityOptions.cs index 5bfd086..5288029 100644 --- a/src/DotNetEd.CoreAdmin/CoreAdminSecurityOptions.cs +++ b/src/DotNetEd.CoreAdmin/CoreAdminSecurityOptions.cs @@ -9,6 +9,12 @@ public class CoreAdminOptions { public string[] RestrictToRoles { get; set; } public Func> CustomAuthorisationMethod { get; set; } + + /// + /// Explicitly allows access without security configuration in Development only. + /// This option is ignored in every other environment and is disabled by default. + /// + public bool AllowUnauthenticatedAccessInDevelopment { get; set; } public bool IsSecuritySet => (RestrictToRoles != null && RestrictToRoles.Length > 0) || CustomAuthorisationMethod != null || CustomAuthorisationMethodWithServiceProvider != null; public string CdnPath { get; set; } diff --git a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Create.cshtml b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Create.cshtml index a07fab6..1d56303 100644 --- a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Create.cshtml +++ b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Create.cshtml @@ -12,7 +12,7 @@ @using (Html.BeginForm("CreateEntityPost", "CoreAdminData", new { id = ViewBag.DbSetName }, -FormMethod.Post, false, +FormMethod.Post, true, new { enctype = "multipart/form-data" })) { @Html.Hidden("dbSetName", ViewBag.DbSetName, new { }) diff --git a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/DeleteEntity.cshtml b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/DeleteEntity.cshtml index de6ee40..8a66d9a 100644 --- a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/DeleteEntity.cshtml +++ b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/DeleteEntity.cshtml @@ -17,7 +17,7 @@ -@using (Html.BeginForm("DeleteEntityPost", "CoreAdminData", new {}, FormMethod.Post)) +@using (Html.BeginForm("DeleteEntityPost", "CoreAdminData", new {}, FormMethod.Post, true, new { })) { @Html.HiddenFor(m => m.DbSetName) @Html.HiddenFor(m => m.Id) diff --git a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Edit.cshtml b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Edit.cshtml index 579f6be..6b2bad1 100644 --- a/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Edit.cshtml +++ b/src/DotNetEd.CoreAdmin/Views/CoreAdminData/Edit.cshtml @@ -12,7 +12,7 @@ @using (Html.BeginForm("EditEntityPost", "CoreAdminData", new { dbSetName = ViewBag.DbSetName, id = ViewBag.Id }, -FormMethod.Post, false, +FormMethod.Post, true, new { enctype = "multipart/form-data" })) { diff --git a/tests/DotNetEd.CoreAdmin.IntegrationTests/BasicTests.cs b/tests/DotNetEd.CoreAdmin.IntegrationTests/BasicTests.cs index f7c3a5c..1451903 100644 --- a/tests/DotNetEd.CoreAdmin.IntegrationTests/BasicTests.cs +++ b/tests/DotNetEd.CoreAdmin.IntegrationTests/BasicTests.cs @@ -1,4 +1,5 @@ using DotNetEd.CoreAdmin.IntegrationTests.TestApp; +using DotNetEd.CoreAdmin; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; @@ -17,7 +18,14 @@ public BasicTests(IntegrationTestsWebHostFactory factory _factory = factory; } - static void ConfigureTestServices(IServiceCollection services) { } + static void ConfigureTestServices(IServiceCollection services) + { + // These UI smoke tests explicitly opt into the Development-only bypass. + services.AddCoreAdmin(new CoreAdminOptions + { + AllowUnauthenticatedAccessInDevelopment = true + }); + } [Fact] public async Task ShowsTestEntitiesOnScreenOnAdminScreen() diff --git a/tests/DotNetEd.CoreAdmin.IntegrationTests/CrudTests.cs b/tests/DotNetEd.CoreAdmin.IntegrationTests/CrudTests.cs index 01666b4..d3353cf 100644 --- a/tests/DotNetEd.CoreAdmin.IntegrationTests/CrudTests.cs +++ b/tests/DotNetEd.CoreAdmin.IntegrationTests/CrudTests.cs @@ -1,7 +1,10 @@ using System; +using DotNetEd.CoreAdmin; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Net.Http; +using System.Text.RegularExpressions; using System.Threading.Tasks; using DotNetEd.CoreAdmin.IntegrationTests.TestApp; using Microsoft.AspNetCore.Hosting; @@ -21,7 +24,116 @@ public CrudTests(IntegrationTestsWebHostFactory factory) _factory = factory; } - static void ConfigureTestServices(IServiceCollection services) { } + static void ConfigureTestServices(IServiceCollection services) + { + // CRUD tests explicitly opt into the Development-only bypass. + services.AddCoreAdmin(new CoreAdminOptions + { + AllowUnauthenticatedAccessInDevelopment = true + }); + } + + private static readonly Regex AntiforgeryTokenRegex = new Regex( + "]*\\bname\\s*=\\s*[\"']__RequestVerificationToken[\"'])(?=[^>]*\\bvalue\\s*=\\s*[\"']([^\"']+)[\"'])[^>]*>", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static async Task PostWithAntiforgeryTokenAsync( + HttpClient client, + string formUrl, + string postUrl, + IDictionary formData) + { + using var formResponse = await client.GetAsync(formUrl); + formResponse.EnsureSuccessStatusCode(); + + var html = await formResponse.Content.ReadAsStringAsync(); + var tokenMatch = AntiforgeryTokenRegex.Match(html); + Assert.True(tokenMatch.Success, $"CSRF token was not found in form: {formUrl}"); + + var data = new Dictionary(formData) + { + ["__RequestVerificationToken"] = WebUtility.HtmlDecode(tokenMatch.Groups[1].Value) + }; + + // WebApplicationFactory's client keeps the antiforgery cookie between GET and POST. + return await client.PostAsync(postUrl, new FormUrlEncodedContent(data)); + } + + [Fact] + public async Task CreateWithoutAntiforgeryToken_IsRejectedAndDoesNotCreateEntity() + { + var dbContext = _factory.Services.GetService(); + var name = Guid.NewGuid().ToString(); + var client = _factory.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + builder.ConfigureTestServices(ConfigureTestServices); + }).CreateClient(); + + var data = new Dictionary { { "Name", name }, { "Id", Guid.NewGuid().ToString() } }; + var response = await client.PostAsync( + "/coreadmindata/CreateEntityPost/testentities?dbSetName=testentities", + new FormUrlEncodedContent(data)); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.False(await dbContext.TestEntities.AnyAsync(entity => entity.Name == name)); + } + + [Fact] + public async Task EditWithoutAntiforgeryToken_IsRejectedAndDoesNotUpdateEntity() + { + var dbContext = _factory.Services.GetService(); + var entity = new TestApp.Entities.TestEntity { Id = Guid.NewGuid(), Name = "Original" }; + dbContext.TestEntities.Add(entity); + await dbContext.SaveChangesAsync(); + + var client = _factory.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + builder.ConfigureTestServices(ConfigureTestServices); + }).CreateClient(); + + var data = new Dictionary + { + { "Name", "Changed" }, + { "Id", entity.Id.ToString() }, + { "dbSetName", "TestEntities" } + }; + var response = await client.PostAsync( + $"/coreadmindata/EditEntityPost/{entity.Id}?dbSetName=TestEntities", + new FormUrlEncodedContent(data)); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + await dbContext.Entry(entity).ReloadAsync(); + Assert.Equal("Original", entity.Name); + } + + [Fact] + public async Task DeleteWithoutAntiforgeryToken_IsRejectedAndDoesNotDeleteEntity() + { + var dbContext = _factory.Services.GetService(); + var entity = new TestApp.Entities.TestEntity { Id = Guid.NewGuid(), Name = "Must remain" }; + dbContext.TestEntities.Add(entity); + await dbContext.SaveChangesAsync(); + + var client = _factory.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + builder.ConfigureTestServices(ConfigureTestServices); + }).CreateClient(); + + var data = new Dictionary + { + { "Id", entity.Id.ToString() }, + { "DbSetName", "testentities" } + }; + var response = await client.PostAsync( + "/coreadmindata/DeleteEntityPost", + new FormUrlEncodedContent(data)); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.True(await dbContext.TestEntities.AnyAsync(item => item.Id == entity.Id)); + } [Fact] public async Task DeleteHappyPath() @@ -42,7 +154,11 @@ public async Task DeleteHappyPath() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "id", idGuid.ToString() }, { "dbSetName", "testentities" } }; - var response = await client.PostAsync("/coreadmindata/DeleteEntityPost", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + $"/coreadmindata/DeleteEntity/{idGuid}?dbSetName=testentities", + "/coreadmindata/DeleteEntityPost", + data); response.EnsureSuccessStatusCode(); // check to see if the item is deleted from DB context @@ -67,7 +183,11 @@ public async Task CreateHappyPath() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "Name", nameGuidString }, { "Id", nameGuidString } }; - var response = await client.PostAsync("/coreadmindata/CreateEntityPost/testentities?dbSetName=testentities", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + "/coreadmindata/Create/testentities", + "/coreadmindata/CreateEntityPost/testentities?dbSetName=testentities", + data); response.EnsureSuccessStatusCode(); @@ -92,7 +212,11 @@ public async Task Create_ChildEntityWithNonNullableFK_HappyPath() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "Name", nameGuidString }, { "Id", nameGuidString } }; - var response = await client.PostAsync("/coreadmindata/CreateEntityPost/testchildentities?dbSetName=testchildentities", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + "/coreadmindata/Create/testchildentities", + "/coreadmindata/CreateEntityPost/testchildentities?dbSetName=testchildentities", + data); response.EnsureSuccessStatusCode(); Assert.True(await dbContext.TestChildEntities.AnyAsync(test => test.Name == nameGuidString)); @@ -101,7 +225,11 @@ public async Task Create_ChildEntityWithNonNullableFK_HappyPath() data = new Dictionary() { { "ParentId", parentId.ToString() }, { "ChildId", idGuid.ToString() }, { "dbSetName", "testparententities" } }; - response = await client.PostAsync("/coreadmindata/CreateEntityPost/testparententities", new FormUrlEncodedContent(data)); + response = await PostWithAntiforgeryTokenAsync( + client, + "/coreadmindata/Create/testparententities", + "/coreadmindata/CreateEntityPost/testparententities", + data); response.EnsureSuccessStatusCode(); @@ -126,7 +254,11 @@ public async Task CreateTestEntityWithValidationError_TooLongName() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "Name", nameString }, { "Id", idGuid.ToString() } }; - var response = await client.PostAsync("/coreadmindata/CreateEntityPost/testentities?dbSetName=testentities", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + "/coreadmindata/Create/testentities", + "/coreadmindata/CreateEntityPost/testentities?dbSetName=testentities", + data); response.EnsureSuccessStatusCode(); // make sure it has not written to DB @@ -151,7 +283,11 @@ public async Task CreateHappyPath_WithAutogeneratedKey() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "Name", nameGuidString } }; - var response = await client.PostAsync("/coreadmindata/CreateEntityPost/TestAutogeneratedKeyEntities?dbSetName=TestAutogeneratedKeyEntities", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + "/coreadmindata/Create/TestAutogeneratedKeyEntities", + "/coreadmindata/CreateEntityPost/TestAutogeneratedKeyEntities?dbSetName=TestAutogeneratedKeyEntities", + data); response.EnsureSuccessStatusCode(); @@ -180,7 +316,11 @@ public async Task UpdateHappyPath() client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); var data = new Dictionary() { { "Name", updatedNameGuid }, { "Id", idGuid.ToString() } }; - var response = await client.PostAsync("/coreadmindata/editentityPost/" + idGuid.ToString() + "?dbSetName=TestEntities", new FormUrlEncodedContent(data)); + var response = await PostWithAntiforgeryTokenAsync( + client, + $"/coreadmindata/EditEntity/{idGuid}?dbSetName=TestEntities", + $"/coreadmindata/editentityPost/{idGuid}?dbSetName=TestEntities", + data); response.EnsureSuccessStatusCode(); // check to see if the item is updated from DB context diff --git a/tests/DotNetEd.CoreAdmin.IntegrationTests/OptionsTests.cs b/tests/DotNetEd.CoreAdmin.IntegrationTests/OptionsTests.cs index 16bf2e4..f573761 100644 --- a/tests/DotNetEd.CoreAdmin.IntegrationTests/OptionsTests.cs +++ b/tests/DotNetEd.CoreAdmin.IntegrationTests/OptionsTests.cs @@ -1,4 +1,5 @@ using DotNetEd.CoreAdmin.IntegrationTests.TestApp; +using DotNetEd.CoreAdmin; using DotNetEd.CoreAdmin.IntegrationTests.TestApp.Entities; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -20,7 +21,14 @@ public OptionsTests(IntegrationTestsWebHostFactory facto _factory = factory; } - static void ConfigureTestServices(IServiceCollection services) { } + static void ConfigureTestServices(IServiceCollection services) + { + // These tests explicitly opt into the Development-only bypass to test UI options. + services.AddCoreAdmin(new CoreAdminOptions + { + AllowUnauthenticatedAccessInDevelopment = true + }); + } [Fact] public async Task ReturnsBuiltInAssetPathWhenCdnOptionsNotSet() @@ -44,7 +52,11 @@ public async Task ReturnsBuiltInAssetPathWhenCdnOptionsNotSet() static void ConfigureTestServicesWithOptionsIgnoringDbSets(IServiceCollection services, IEnumerable dbSetsToIgnore) { - services.AddCoreAdmin(new CoreAdminOptions() { IgnoreEntityTypes = dbSetsToIgnore }); + services.AddCoreAdmin(new CoreAdminOptions + { + IgnoreEntityTypes = dbSetsToIgnore, + AllowUnauthenticatedAccessInDevelopment = true + }); } [Fact] public async Task IgnoreEntityTypes_DoesNotIncludeIgnoredDbSets() diff --git a/tests/DotNetEd.CoreAdmin.IntegrationTests/SecurityTests.cs b/tests/DotNetEd.CoreAdmin.IntegrationTests/SecurityTests.cs index ebabe76..951c0f8 100644 --- a/tests/DotNetEd.CoreAdmin.IntegrationTests/SecurityTests.cs +++ b/tests/DotNetEd.CoreAdmin.IntegrationTests/SecurityTests.cs @@ -1,4 +1,6 @@ using DotNetEd.CoreAdmin.IntegrationTests.TestApp; +using DotNetEd.CoreAdmin; +using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; @@ -18,16 +20,25 @@ public SecurityTests(IntegrationTestsWebHostFactory fact _factory = factory; } - static void ConfigureTestServices(IServiceCollection services) { } + static void ConfigureTestServices(IServiceCollection services) + { + // The warning-page test explicitly opts into the Development-only bypass. + services.AddCoreAdmin(new CoreAdminOptions + { + AllowUnauthenticatedAccessInDevelopment = true + }); + } static void ConfigureTestServicesWithSecurity(IServiceCollection services) { services.AddCoreAdmin("TestRole"); } - [Obsolete] static void ConfigureTestServicesWithSecurityAuthMethod(IServiceCollection services, Func> authMethod) { - services.AddCoreAdmin(authMethod); + services.AddCoreAdmin(new CoreAdminOptions + { + CustomAuthorisationMethod = authMethod + }); } static void ConfigureTestServicesWithSecurityAndAlternativeTestRole(IServiceCollection services) @@ -57,6 +68,18 @@ public async Task ShowsWarningMessageInDevelopmentModeWhenNoSecuritySet() } + [Fact] + public async Task ReturnsUnauthorizedInDevelopmentModeWhenNoSecuritySetAndBypassNotEnabled() + { + var client = _factory.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + }).CreateClient(); + + using var response = await client.GetAsync("/coreadmin"); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + [Fact] public async Task DoesNotShowWarningMessageInDevelopmentModeWhenSecurityIsSet() { @@ -101,7 +124,10 @@ public async Task ReturnsUnauthorizedWhenInProductionButNoSecuritySet() { // Arrange var client = _factory.WithWebHostBuilder(builder => - builder.ConfigureTestServices(ConfigureTestServices)).CreateClient(); + { + builder.UseEnvironment("Production"); + builder.ConfigureTestServices(ConfigureTestServices); + }).CreateClient(); // Act var response = await client.GetAsync("/coreadmin"); @@ -126,7 +152,6 @@ public async Task SuccessStatusCodeAndUsesRoleWhenInProductionAndRoleCheckSet() } [Fact] - [Obsolete] public async Task SuccessStatusCodeAndCallsCustomAuthMethodInProductionAndAuthMethodCheckSet() { bool authCalled = false; @@ -147,7 +172,37 @@ public async Task SuccessStatusCodeAndCallsCustomAuthMethodInProductionAndAuthMe } [Fact] - [Obsolete] + public async Task AwaitsDelayedCustomAuthorizationBeforeExecutingController() + { + var authorizationStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var authorizationDecision = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var authMethod = new Func>(async () => + { + authorizationStarted.TrySetResult(true); + return await authorizationDecision.Task; + }); + + var client = _factory.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Production"); + builder.ConfigureTestServices(services => + ConfigureTestServicesWithSecurityAuthMethod(services, authMethod)); + }).CreateClient(); + + var responseTask = client.GetAsync("/coreadmindata/index/testentities"); + await authorizationStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await Task.Delay(100); + + // A protected controller action must not finish while authorization is pending. + Assert.False(responseTask.IsCompleted); + + authorizationDecision.TrySetResult(false); + using var response = await responseTask.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] public async Task ReturnsUnauthorizedWhenInProductionCustomAuthMethodFails() { bool authCalled = false;