netmash/NDB.Security.Authentication.../AuthenticationExtensions.cs

43 lines
1.8 KiB
C#

using IdentityServer.Wrapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Netmash.Security.Authentication.Identity.Abstractions;
using System;
namespace Netmash.Security.Authentication.Identity
{
public static class AuthenticationExtensions
{
public static IServiceCollection AddIdentityAuthentication(this IServiceCollection services, string identityServerBaseAddress)
{
services.AddIdentityAuthentication(identityServerBaseAddress, new Models.AuthenticationOptions());
return services;
}
public static IServiceCollection AddIdentityAuthentication(this IServiceCollection services, string identityServerBaseAddress, IAuthenticationOptions authenticationOptions)
{
Validate(identityServerBaseAddress, authenticationOptions);
// Identity server
services.UseIdentityServices(identityServerBaseAddress);
services.AddSingleton(authenticationOptions);
// configure authentication
services.AddAuthentication("IdentityAuthentication")
.AddScheme<AuthenticationSchemeOptions, IdentityAuthenticationHandler>("IdentityAuthentication", null);
return services;
}
private static void Validate(string identityServerBaseAddress, IAuthenticationOptions authenticationOptions)
{
if (string.IsNullOrEmpty(identityServerBaseAddress))
throw new ArgumentException("Identity server base address must be provided.");
var guestFuncDefined = authenticationOptions.AuthenticateAsGuest != null;
if (guestFuncDefined && string.IsNullOrEmpty(authenticationOptions.GuestUserName))
throw new ArgumentException("Guest function is defined, but guest user name is not set.");
}
}
}