using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using MaxInventory.Authentication.Providers.AdfsWsFed; using MaxInventory.Authentication.Abstractions; using MaxInventory.Authentication.Configuration; using MaxInventory.Authentication.Core; using MaxInventory.Authentication.Providers.Oidc; using MaxInventory.Authentication.Providers.Cas; namespace MaxInventory.Authentication.Extensions { public static class AuthenticationServiceCollectionExtensions { public static IServiceCollection AddAuthentication( this IServiceCollection services, IConfiguration configuration, Action? configureAuthorization = null) { services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddScoped(); services.AddScoped(); services.AddHttpClient(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddSingleton(); services.TryAddSingleton(); var authMode = configuration[AuthEnvironment.AuthMode] ?? AuthModes.Oidc; var challengeScheme = authMode.ToUpperInvariant() switch { AuthModes.Oidc => OidcAuthProvider.Scheme, AuthModes.WsFed => AdfsWsFedAuthProvider.Scheme, AuthModes.Cas => CasAuthProvider.Scheme, _ => throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}") }; var authBuilder = services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = challengeScheme; }); authBuilder.AddCookie(options => { options.Cookie.Name = "secure-network.auth"; options.AccessDeniedPath = "/access-denied"; options.EventsType = typeof(AdminCookieValidationEvents); }); var providers = new IAuthProvider[] { new OidcAuthProvider(), new AdfsWsFedAuthProvider(), new CasAuthProvider() }; var provider = providers.FirstOrDefault(p => p.Mode.Equals(authMode, StringComparison.OrdinalIgnoreCase)); if (provider is null) { throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}"); } provider.Configure(authBuilder, configuration); services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireRole(AuthRoles.View,AuthRoles.EditAdd, AuthRoles.Admin) .Build(); options.AddPolicy("ViewOnly", policy => policy.RequireRole(AuthRoles.View, AuthRoles.EditAdd, AuthRoles.Admin)); options.AddPolicy("CanEdit", policy => policy.RequireRole(AuthRoles.EditAdd, AuthRoles.Admin)); options.AddPolicy("AdminOnly", PolicySchemeHandler => PolicySchemeHandler.RequireRole(AuthRoles.Admin)); configureAuthorization?.Invoke(options); }); return services; } } } //Triggering release.