using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Netmash.Security.Authentication.Identity; using Netmash.Security.Authentication.Identity.Models; using System.Linq; namespace Netmash.Test.Api.Extensions { public static class AuthenticationExtensions { private record GuestRoute(string Route, int PathElements); private static readonly GuestRoute[] _resourcesRoutes = new GuestRoute[] { new GuestRoute("/resources", 1), new GuestRoute("/images", 1), new GuestRoute("/spot", 2) }; public static IServiceCollection AddIdentityAuthentication(this IServiceCollection services, string identityServerBaseAddress) { var authenticationOptions = new AuthenticationOptions() { AuthenticateAsGuest = (HttpRequest request) => { var authenticateAsGuest = AuthenticateAsGuest(request); return authenticateAsGuest; }, GuestUserName = "Guest", GuestUserId = -111, AcceptTokenFromQuery = true }; services.AddIdentityAuthentication(identityServerBaseAddress, authenticationOptions); return services; } private static bool AuthenticateAsGuest(HttpRequest request) { if (!request.Path.HasValue) return false; var guestRoute = _resourcesRoutes.FirstOrDefault(z => request.Path.Value.StartsWith(z.Route)); if (guestRoute == null) return false; var resourceRequestedById = request.Query.Count > 0 && request.Query.ContainsKey("id"); if (resourceRequestedById) return false; var resourceRequestedByCode = request.Query.Count > 0 && request.Query.ContainsKey("code"); if (resourceRequestedByCode) return true; var resourceRequestedByName = request.Path.Value.Replace(guestRoute.Route, string.Empty).Substring(1).Split("/").Length == guestRoute.PathElements; if (resourceRequestedByName) return true; return false; } } }