Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for reading default scheme from config #41987

Merged
merged 5 commits into from
Jun 13, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/DefaultBuilder/src/WebApplicationAuthenticationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,34 @@ public WebApplicationAuthenticationBuilder(IServiceCollection services) : base(s

public override AuthenticationBuilder AddPolicyScheme(string authenticationScheme, string? displayName, Action<PolicySchemeOptions> configureOptions)
{
RegisterServices(authenticationScheme);
RegisterServices();
return base.AddPolicyScheme(authenticationScheme, displayName, configureOptions);
}

public override AuthenticationBuilder AddRemoteScheme<TOptions, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string authenticationScheme, string? displayName, Action<TOptions>? configureOptions)
{
RegisterServices(authenticationScheme);
RegisterServices();
return base.AddRemoteScheme<TOptions, THandler>(authenticationScheme, displayName, configureOptions);
}

public override AuthenticationBuilder AddScheme<TOptions, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string authenticationScheme, string? displayName, Action<TOptions>? configureOptions)
{
RegisterServices(authenticationScheme);
RegisterServices();
return base.AddScheme<TOptions, THandler>(authenticationScheme, displayName, configureOptions);
}

public override AuthenticationBuilder AddScheme<TOptions, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string authenticationScheme, Action<TOptions>? configureOptions)
{
RegisterServices(authenticationScheme);
RegisterServices();
return base.AddScheme<TOptions, THandler>(authenticationScheme, configureOptions);
}

private void RegisterServices(string authenticationScheme)
private void RegisterServices()
{
if (!IsAuthenticationConfigured)
{
IsAuthenticationConfigured = true;
Services.AddAuthentication(authenticationScheme);
Services.AddAuthentication();
Services.AddAuthorization();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ public interface IAuthenticationConfigurationProvider
/// Returns the specified <see cref="ConfigurationSection"/> object.
/// </summary>
/// <param name="authenticationScheme">The path to the section to be returned.</param>
/// <returns>The specified <see cref="ConfigurationSection"/> object, or null if the requested section does not exist.</returns>
/// <returns>The specified <see cref="IConfiguration"/> object, or null if the requested section does not exist.</returns>
IConfiguration GetAuthenticationSchemeConfiguration(string authenticationScheme);

/// <summary>
/// Returns the <see cref="ConfigurationSection"/> where authentication
/// options are stored.
/// </summary>
/// <returns>The specified <see cref="IConfiguration"/> object, or null if the requested section does not exist.</returns>
IConfiguration GetAuthenticationConfiguration();
captainsafia marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#nullable enable
Microsoft.AspNetCore.Authentication.IAuthenticationConfigurationProvider
Microsoft.AspNetCore.Authentication.IAuthenticationConfigurationProvider.GetAuthenticationConfiguration() -> Microsoft.Extensions.Configuration.IConfiguration!
Microsoft.AspNetCore.Authentication.IAuthenticationConfigurationProvider.GetAuthenticationSchemeConfiguration(string! authenticationScheme) -> Microsoft.Extensions.Configuration.IConfiguration!
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public class AuthenticationBuilder
/// </summary>
/// <param name="services">The services being configured.</param>
public AuthenticationBuilder(IServiceCollection services)
=> Services = services;
{
Services = services;
// Always try to read global authentication options from configuration
Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<AuthenticationOptions>, AuthenticationConfigureOptions>());
}

/// <summary>
/// The services being configured.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication;

internal sealed class AuthenticationConfigureOptions : IConfigureOptions<AuthenticationOptions>
{
private readonly IAuthenticationConfigurationProvider _authenticationConfigurationProvider;
private const string DefaultSchemeKey = "DefaultScheme";

public AuthenticationConfigureOptions(IAuthenticationConfigurationProvider configurationProvider)
{
_authenticationConfigurationProvider = configurationProvider;
}

public void Configure(AuthenticationOptions options)
{
var authenticationConfig = _authenticationConfigurationProvider.GetAuthenticationConfiguration();
var defaultScheme = authenticationConfig[DefaultSchemeKey];
if (!string.IsNullOrEmpty(defaultScheme))
{
options.DefaultScheme = defaultScheme;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@ namespace Microsoft.AspNetCore.Authentication;
internal sealed class DefaultAuthenticationConfigurationProvider : IAuthenticationConfigurationProvider
{
private readonly IConfiguration _configuration;
private const string AuthenticationKey = "Authentication";
private const string AuthenticationSchemesKey = "Authentication:Schemes";

public DefaultAuthenticationConfigurationProvider(IConfiguration configuration)
{
_configuration = configuration;
}

public IConfiguration GetAuthenticationConfiguration()
captainsafia marked this conversation as resolved.
Show resolved Hide resolved
{
return _configuration.GetSection(AuthenticationKey);
}

public IConfiguration GetAuthenticationSchemeConfiguration(string authenticationScheme)
{
return _configuration.GetSection($"Authentication:Schemes:{authenticationScheme}");
return _configuration.GetSection($"{AuthenticationSchemesKey}:{authenticationScheme}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

builder.Authentication.AddJwtBearer();
builder.Authentication.AddJwtBearer("ClaimedDetails");
builder.Authentication.AddJwtBearer("InvalidScheme");

builder.Services.AddAuthorization(options =>
options.AddPolicy("is_admin", policy =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
}
},
"Authentication": {
"DefaultScheme": "ClaimedDetails",
"Schemes": {
"Bearer": {
"Audiences": [
Expand All @@ -20,7 +21,14 @@
"http://localhost:5259"
],
"ClaimsIssuer": "dotnet-user-jwts"
},
"InvalidScheme": {
"Audiences": [
"https://localhost:7259",
"http://localhost:5259"
],
"ClaimsIssuer": "invalid-issuer"
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -183,6 +184,7 @@ private HttpContext GetHttpContext(
serviceCollection.AddOptions();
serviceCollection.AddLogging();
serviceCollection.AddAuthentication();
serviceCollection.AddSingleton<IConfiguration>(new ConfigurationManager());
registerServices?.Invoke(serviceCollection);

var serviceProvider = serviceCollection.BuildServiceProvider();
Expand Down
3 changes: 2 additions & 1 deletion src/Security/Authentication/test/CertificateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
Expand All @@ -24,7 +25,7 @@ public class ClientCertificateAuthenticationTests
[Fact]
public async Task VerifySchemeDefaults()
{
var services = new ServiceCollection();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication().AddCertificate();
var sp = services.BuildServiceProvider();
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
Expand Down
37 changes: 37 additions & 0 deletions src/Security/Authentication/test/JwtBearerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authentication.Tests;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -883,6 +885,41 @@ public async Task ExpirationAndIssuedNullWhenMinOrMaxValue()
Assert.Equal(JsonValueKind.Null, dom.RootElement.GetProperty("issued").ValueKind);
}

[Fact]
public async Task ForwardSchemeOverridesSchemeFromConfig()
{
// Arrange
var defaultSchemeFromConfig = "DefaultSchemeFromConfig";
var defaultSchemeFromForward = "DefaultSchemeFromForward";
var services = new ServiceCollection().AddLogging();
var config = new ConfigurationBuilder().AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("Authentication:DefaultScheme", defaultSchemeFromConfig)
}).Build();
services.AddSingleton<IConfiguration>(config);

// Act
var builder = services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>(defaultSchemeFromForward, defaultSchemeFromForward);
});
builder.AddJwtBearer(defaultSchemeFromConfig, o => o.ForwardAuthenticate = defaultSchemeFromForward);
var forwardAuthentication = new TestHandler();
services.AddSingleton(forwardAuthentication);

var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;

// Assert
Assert.Equal(0, forwardAuthentication.AuthenticateCount);
await context.AuthenticateAsync();
Assert.Equal(1, forwardAuthentication.AuthenticateCount);
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
var defaultSchemeFromServices = await schemeProvider.GetDefaultAuthenticateSchemeAsync();
Assert.Equal(defaultSchemeFromConfig, defaultSchemeFromServices.Name);
}

class InvalidTokenValidator : ISecurityTokenValidator
{
public InvalidTokenValidator()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Expand All @@ -27,8 +28,7 @@ private void ConfigureDefaults(OpenIdConnectOptions o)
[Fact]
public async Task CanForwardDefault()
{
var services = new ServiceCollection().AddLogging();

var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -71,8 +71,7 @@ public async Task CanForwardDefault()
[Fact]
public async Task ForwardSignInThrows()
{
var services = new ServiceCollection().AddLogging();

var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -101,8 +100,7 @@ public async Task ForwardSignInThrows()
[Fact]
public async Task ForwardSignOutWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();

var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -142,8 +140,7 @@ public async Task ForwardSignOutWinsOverDefault()
[Fact]
public async Task ForwardForbidWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();

var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -183,8 +180,7 @@ public async Task ForwardForbidWinsOverDefault()
[Fact]
public async Task ForwardAuthenticateWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();

var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -224,7 +220,7 @@ public async Task ForwardAuthenticateWinsOverDefault()
[Fact]
public async Task ForwardChallengeWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -264,7 +260,7 @@ public async Task ForwardChallengeWinsOverDefault()
[Fact]
public async Task ForwardSelectorWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -319,7 +315,7 @@ public async Task ForwardSelectorWinsOverDefault()
[Fact]
public async Task NullForwardSelectorUsesDefault()
{
var services = new ServiceCollection().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down Expand Up @@ -374,7 +370,7 @@ public async Task NullForwardSelectorUsesDefault()
[Fact]
public async Task SpecificForwardWinsOverSelectorAndDefault()
{
var services = new ServiceCollection().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
Expand Down
11 changes: 6 additions & 5 deletions src/Security/Authentication/test/PolicyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Expand Down Expand Up @@ -53,7 +54,7 @@ public async Task CanDispatch()
[Fact]
public async Task DefaultTargetSelectorWinsOverDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
Expand Down Expand Up @@ -109,7 +110,7 @@ public async Task DefaultTargetSelectorWinsOverDefaultTarget()
[Fact]
public async Task NullDefaultTargetSelectorFallsBacktoDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
Expand Down Expand Up @@ -165,7 +166,7 @@ public async Task NullDefaultTargetSelectorFallsBacktoDefaultTarget()
[Fact]
public async Task SpecificTargetAlwaysWinsOverDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
Expand Down Expand Up @@ -226,7 +227,7 @@ public async Task SpecificTargetAlwaysWinsOverDefaultTarget()
[Fact]
public async Task VirtualSchemeTargetsForwardWithDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
Expand Down Expand Up @@ -278,7 +279,7 @@ public async Task VirtualSchemeTargetsForwardWithDefaultTarget()
[Fact]
public async Task VirtualSchemeTargetsOverrideDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
var services = new ServiceCollection().ConfigureAuthTestServices();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
Expand Down
Loading