Skip to content

Commit 189a4ce

Browse files
authored
Fix auto-registeration of authN and authZ middlewares (#42250)
* Fix auto-registeration of authN and authZ middlewares * Update tests * Apply suggestions from code review * Spruce up tests
1 parent e00b58e commit 189a4ce

File tree

3 files changed

+78
-2
lines changed

3 files changed

+78
-2
lines changed

src/DefaultBuilder/src/WebApplicationBuilder.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,8 +180,11 @@ private void ConfigureApplication(WebHostBuilderContext context, IApplicationBui
180180
// Don't add more than one instance of the middleware
181181
if (!_builtApplication.Properties.ContainsKey(AuthenticationMiddlewareSetKey))
182182
{
183-
_builtApplication.UseAuthentication();
184-
_builtApplication.UseAuthorization();
183+
// The Use invocations will set the property on the outer pipeline,
184+
// but we want to set it on the inner pipeline as well
185+
_builtApplication.Properties[AuthenticationMiddlewareSetKey] = true;
186+
app.UseAuthentication();
187+
app.UseAuthorization();
185188
}
186189
}
187190

src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/Microsoft.AspNetCore.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
<ItemGroup>
88
<Reference Include="Microsoft.AspNetCore" />
99
<Reference Include="Microsoft.AspNetCore.TestHost" />
10+
<Reference Include="Microsoft.AspNetCore.Authorization.Policy" />
1011
<Content Include="Microsoft.AspNetCore.TestHost.StaticWebAssets.xml" CopyToOutputDirectory="PreserveNewest" />
1112
</ItemGroup>
1213

src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/WebApplicationTests.cs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,13 @@
55
using System.Diagnostics;
66
using System.Diagnostics.Tracing;
77
using System.Net;
8+
using System.Net.Http;
89
using System.Reflection;
10+
using System.Security.Claims;
911
using System.Text;
12+
using System.Text.Encodings.Web;
13+
using Microsoft.AspNetCore.Authentication;
14+
using Microsoft.AspNetCore.Authorization;
1015
using Microsoft.AspNetCore.Builder;
1116
using Microsoft.AspNetCore.HostFiltering;
1217
using Microsoft.AspNetCore.Hosting;
@@ -1976,6 +1981,73 @@ public void CanObserveDefaultServicesInServiceCollection()
19761981
Assert.Contains(builder.Services, service => service.ServiceType == typeof(ILogger<>));
19771982
}
19781983

1984+
[Fact]
1985+
public async Task RegisterAuthMiddlewaresCorrectly()
1986+
{
1987+
var helloEndpointCalled = false;
1988+
var customMiddlewareExecuted = false;
1989+
var username = "foobar";
1990+
1991+
var builder = WebApplication.CreateBuilder();
1992+
builder.Services.AddAuthenticationCore(o =>
1993+
{
1994+
o.DefaultScheme = "testSchemeName";
1995+
});
1996+
builder.Authentication.AddScheme<AuthenticationSchemeOptions, UberHandler>("testSchemeName", "testDisplayName", _ => { });
1997+
builder.WebHost.UseTestServer();
1998+
await using var app = builder.Build();
1999+
2000+
app.Use(next =>
2001+
{
2002+
return async context =>
2003+
{
2004+
// IAuthenticationFeature is added by the authentication middleware
2005+
// during invocation. This middleware should run after authentication
2006+
// and be able to access the feature.
2007+
var authFeature = context.Features.Get<IAuthenticationFeature>();
2008+
Assert.NotNull(authFeature);
2009+
customMiddlewareExecuted = true;
2010+
Assert.Equal(username, context.User.Identity.Name);
2011+
await next(context);
2012+
};
2013+
});
2014+
2015+
app.MapGet("/hello", (ClaimsPrincipal user) =>
2016+
{
2017+
helloEndpointCalled = true;
2018+
Assert.Equal(username, user.Identity.Name);
2019+
}).AllowAnonymous();
2020+
2021+
await app.StartAsync();
2022+
var client = app.GetTestClient();
2023+
await client.GetStringAsync($"/hello?username={username}");
2024+
2025+
Assert.True(helloEndpointCalled);
2026+
Assert.True(customMiddlewareExecuted);
2027+
}
2028+
2029+
private class UberHandler : AuthenticationHandler<AuthenticationSchemeOptions>
2030+
{
2031+
public UberHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { }
2032+
2033+
protected override Task HandleChallengeAsync(AuthenticationProperties properties) => Task.CompletedTask;
2034+
2035+
protected override Task HandleForbiddenAsync(AuthenticationProperties properties) => Task.CompletedTask;
2036+
2037+
public Task<bool> HandleRequestAsync() => Task.FromResult(false);
2038+
2039+
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
2040+
{
2041+
var username = Request.Query["username"];
2042+
var principal = new ClaimsPrincipal();
2043+
var id = new ClaimsIdentity();
2044+
id.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, username));
2045+
principal.AddIdentity(id);
2046+
return Task.FromResult(AuthenticateResult.Success(
2047+
new AuthenticationTicket(principal, "custom")));
2048+
}
2049+
}
2050+
19792051
public class RandomConfigurationSource : IConfigurationSource
19802052
{
19812053
public int ProvidersBuilt { get; set; }

0 commit comments

Comments
 (0)