// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { /// /// Extension methods for setting up antiforgery services in an . /// public static class AntiforgeryServiceCollectionExtensions { /// /// Adds antiforgery services to the specified . /// /// The to add services to. /// The so that additional calls can be chained. public static IServiceCollection AddAntiforgery(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddDataProtection(); // Don't overwrite any options setups that a user may have added. services.TryAddEnumerable( ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton>(serviceProvider => { var provider = serviceProvider.GetRequiredService(); var policy = new AntiforgerySerializationContextPooledObjectPolicy(); return provider.Create(policy); }); return services; } /// /// Adds antiforgery services to the specified . /// /// The to add services to. /// An to configure the provided . /// The so that additional calls can be chained. public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } services.AddAntiforgery(); services.Configure(setupAction); return services; } } }