netmash/Netmash.Security.Authentica.../AuthenticationExtensions.cs

43 lines
1.8 KiB
C#
Raw Normal View History

2020-12-21 22:58:40 +02:00
using IdentityServer.Wrapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
2023-01-12 01:01:36 +02:00
using Netmash.Security.Authentication.Identity.Abstractions;
2020-12-21 22:58:40 +02:00
using System;
2023-01-12 01:01:36 +02:00
namespace Netmash.Security.Authentication.Identity
2020-12-21 22:58:40 +02:00
{
public static class AuthenticationExtensions
2020-12-21 22:58:40 +02:00
{
public static IServiceCollection AddIdentityAuthentication(this IServiceCollection services, string identityServerBaseAddress)
2020-12-21 22:58:40 +02:00
{
services.AddIdentityAuthentication(identityServerBaseAddress, new Models.AuthenticationOptions());
return services;
}
public static IServiceCollection AddIdentityAuthentication(this IServiceCollection services, string identityServerBaseAddress, IAuthenticationOptions authenticationOptions)
{
Validate(identityServerBaseAddress, authenticationOptions);
2020-12-21 22:58:40 +02:00
// Identity server
services.UseIdentityServices(identityServerBaseAddress);
services.AddSingleton(authenticationOptions);
2020-12-21 22:58:40 +02:00
// configure authentication
services.AddAuthentication("IdentityAuthentication")
.AddScheme<AuthenticationSchemeOptions, IdentityAuthenticationHandler>("IdentityAuthentication", null);
2020-12-21 22:58:40 +02:00
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.");
}
2020-12-21 22:58:40 +02:00
}
}