2020-12-21 22:58:40 +02:00
|
|
|
|
using IdentityServer.Wrapper;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2021-06-26 21:20:49 +03:00
|
|
|
|
using NDB.Security.Authentication.Identity.Abstractions;
|
2020-12-21 22:58:40 +02:00
|
|
|
|
using System;
|
|
|
|
|
|
|
|
|
|
namespace NDB.Security.Authentication.Identity
|
|
|
|
|
{
|
|
|
|
|
public static class BasicAuthenticationExtensions
|
|
|
|
|
{
|
|
|
|
|
public static IServiceCollection AddBasicAuthentication(this IServiceCollection services, string identityServerBaseAddress)
|
|
|
|
|
{
|
2021-06-26 21:20:49 +03:00
|
|
|
|
services.AddBasicAuthentication(identityServerBaseAddress, new Services.AuthenticationOptions());
|
|
|
|
|
return services;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static IServiceCollection AddBasicAuthentication(this IServiceCollection services, string identityServerBaseAddress, IAuthenticationOptions authenticationOptions)
|
|
|
|
|
{
|
|
|
|
|
Validate(identityServerBaseAddress, authenticationOptions);
|
2020-12-21 22:58:40 +02:00
|
|
|
|
|
|
|
|
|
// Identity server
|
|
|
|
|
services.UseIdentityServices(identityServerBaseAddress);
|
2021-06-26 21:20:49 +03:00
|
|
|
|
services.AddSingleton(authenticationOptions);
|
2020-12-21 22:58:40 +02:00
|
|
|
|
|
|
|
|
|
// configure basic authentication
|
|
|
|
|
services.AddAuthentication("BasicAuthentication")
|
|
|
|
|
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
|
|
|
|
|
|
|
|
|
|
return services;
|
|
|
|
|
}
|
2021-06-26 21:20:49 +03:00
|
|
|
|
|
|
|
|
|
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.");
|
|
|
|
|
}
|
2020-12-21 22:58:40 +02:00
|
|
|
|
}
|
|
|
|
|
}
|