// 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.Authentication;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.DependencyInjection
{
///
/// Extension methods for setting up authentication services in an .
///
public static class AuthenticationServiceCollectionExtensions
{
public static AuthenticationBuilder AddAuthentication(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddAuthenticationCore();
services.AddDataProtection();
services.AddWebEncoders();
services.TryAddSingleton();
return new AuthenticationBuilder(services);
}
public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, string defaultScheme)
=> services.AddAuthentication(o => o.DefaultScheme = defaultScheme);
public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, Action configureOptions) {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var builder = services.AddAuthentication();
services.Configure(configureOptions);
return builder;
}
// Used to ensure that there's always a sign in scheme
private class EnsureSignInScheme : IPostConfigureOptions where TOptions : RemoteAuthenticationOptions
{
private readonly AuthenticationOptions _authOptions;
public EnsureSignInScheme(IOptions authOptions)
{
_authOptions = authOptions.Value;
}
public void PostConfigure(string name, TOptions options)
{
options.SignInScheme = options.SignInScheme ?? _authOptions.DefaultSignInScheme;
}
}
}
}