Пример #1
0
        public static void CreateTestHost(string userName, IEnumerable <Claim> claims, string url, TestServer sut, ITestOutputHelper testOutputHelper, out TestHost host, out MockHttpMessageHandler mockHttp)
        {
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var jsRuntimeMock = new Mock <IJSRuntime>();

            host = new TestHost();
            var httpMock = host.AddMockHttp();

            mockHttp = httpMock;
            var localizerMock = new Mock <ISharedStringLocalizerAsync>();

            localizerMock.Setup(m => m[It.IsAny <string>()]).Returns((string key) => new LocalizedString(key, key));
            localizerMock.Setup(m => m[It.IsAny <string>(), It.IsAny <object[]>()]).Returns((string key, object[] p) => new LocalizedString(key, string.Format(key, p)));

            host.ConfigureServices(services =>
            {
                var httpClient       = sut.CreateClient();
                var appConfiguration = CreateApplicationConfiguration(httpClient);

                WebAssemblyHostBuilderExtensions.ConfigureServices(services, appConfiguration, appConfiguration.Get <Settings>(), httpClient.BaseAddress.ToString());

                sut.Services.GetRequiredService <TestUserService>()
                .SetTestUser(true, claims.Select(c => new Claim(c.Type, c.Value)));

                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(new TestLoggerProvider(testOutputHelper));
                })
                .AddTransient(p => sut.CreateHandler())
                .AddIdentityServer4AdminHttpStores(p =>
                {
                    var client = new HttpClient(new BaseAddressAuthorizationMessageHandler(p.GetRequiredService <IAccessTokenProvider>(),
                                                                                           p.GetRequiredService <NavigationManager>())
                    {
                        InnerHandler = sut.CreateHandler()
                    })
                    {
                        BaseAddress = new Uri(httpClient.BaseAddress, "api")
                    };
                    return(Task.FromResult(client));
                })
                .AddSingleton(p => new TestNavigationManager(uri: url))
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => navigationInterceptionMock.Object)
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton <Settings>()
                .AddSingleton(localizerMock.Object)
                .AddSingleton <SignOutSessionStateManager, FakeSignOutSessionStateManager>()
                .AddSingleton <IAccessTokenProviderAccessor, AccessTokenProviderAccessor>()
                .AddSingleton <IAccessTokenProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton <AuthenticationStateProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton(p => new FakeAuthenticationStateProvider(p.GetRequiredService <NavigationManager>(),
                                                                       userName,
                                                                       claims));
            });
        }
Пример #2
0
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();

            builder
            .RegisterBlazorMauiWebView()
            .UseMauiApp <App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            });

            var configuration = builder.Configuration;

            configuration.AddInMemoryCollection(new Dictionary <string, string>
            {
                ["apiBaseUrl"] = "https://theidserver-duende.herokuapp.com/api",
                ["authenticationPaths:remoteRegisterPath"] = "/identity/account/register",
                ["authenticationPaths:remoteProfilePath"]  = "/identity/account/manage",
                ["userOptions:roleClaim"]                 = "role",
                ["providerOptions:authority"]             = "https://theidserver-duende.herokuapp.com",
                ["providerOptions:clientId"]              = "theidserveradmin",
                ["providerOptions:defaultScopes"]         = @" [
      ""openid"",
      ""profile"",
      ""theidserveradminapi""
    ]",
                ["providerOptions:postLogoutRedirectUri"] = "https://theidserver-duende.herokuapp.com/authentication/logout-callback",
                ["providerOptions:postLogoutRedirectUri"] = "https://theidserver-duende.herokuapp.com/authentication/login-callback",
                ["providerOptions:responseType"]          = "code",
                ["welcomeContenUrl"]         = "https://theidserver-duende.herokuapp.com/api/welcomefragment",
                ["settingsOptions:typeName"] = "Aguacongas.TheIdServer.BlazorApp.Models.ServerConfig, Aguacongas.TheIdServer.BlazorApp.Infrastructure",
                ["settingsOptions:apiUrl"]   = "https://theidserver-duende.herokuapp.com/api/api/configuration",
                ["menuOptions:showSettings"] = "true"
            });

            var settings = configuration.Get <Settings>();

            var services = builder.Services.AddBlazorWebView();

            WebAssemblyHostBuilderExtensions.ConfigureServices(services, configuration, settings);


            return(builder.Build());
        }
Пример #3
0
 public void Configure(IAppHostBuilder appBuilder)
 {
     appBuilder
     .UseFormsCompatibility()
     .RegisterBlazorMauiWebView(typeof(Startup).Assembly)
     .UseMicrosoftExtensionsServiceProviderFactory()
     .UseMauiApp <App>()
     .ConfigureFonts(fonts =>
     {
         fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
     })
     .ConfigureAppConfiguration(builder =>
     {
         builder.AddInMemoryCollection(new Dictionary <string, string>
         {
             ["administratorEmail"] = "*****@*****.**",
             ["apiBaseUrl"]         = "https://localhost:5443/api",
             ["authenticationPaths:remoteRegisterPath"] = "/identity/account/register",
             ["authenticationPaths:remoteProfilePath"]  = "/identity/account/manage",
             ["loggingOptions:minimum"]                = "",
             ["userOptions:roleClaim"]                 = "role",
             ["providerOptions:authority"]             = "https://localhost:5443/",
             ["providerOptions:clientId"]              = "https://localhost:5443/",
             ["providerOptions:defaultScopes:0"]       = "openid",
             ["providerOptions:defaultScopes:1"]       = "profile",
             ["providerOptions:defaultScopes:2"]       = "theidserveradminapi",
             ["providerOptions:postLogoutRedirectUri"] = "/authentication/logout-callback",
             ["providerOptions:redirectUri"]           = "/authentication/login-callback",
             ["providerOptions:responseType"]          = "code",
             ["welcomeContenUrl"] = "/api/welcomefragment",
         });
     })
     .ConfigureServices((context, services) =>
     {
         services.AddBlazorWebView();
         var settings = context.Configuration.Get <Settings>();
         WebAssemblyHostBuilderExtensions.ConfigureServices(services, context.Configuration, settings, settings.ApiBaseUrl);
     });
 }
Пример #4
0
        public void ConfigureTestContext(string userName,
                                         IEnumerable <Claim> claims,
                                         TestContext testContext)
        {
            testContext.JSInterop.Mode = JSRuntimeMode.Loose;
            testContext.Services.AddScoped <JSRuntimeImpl>();

            var authContext = testContext.AddTestAuthorization();

            authContext.SetAuthorized(userName);
            authContext.SetClaims(claims.ToArray());
            authContext.SetPolicies(claims.Where(c => c.Type == "role").Select(c => c.Value).ToArray());

            var localizerMock = new Mock <ISharedStringLocalizerAsync>();

            localizerMock.Setup(m => m[It.IsAny <string>()]).Returns((string key) => new LocalizedString(key, key));
            localizerMock.Setup(m => m[It.IsAny <string>(), It.IsAny <object[]>()]).Returns((string key, object[] p) => new LocalizedString(key, string.Format(key, p)));

            var services         = testContext.Services;
            var httpClient       = CreateClient();
            var appConfiguration = TestUtils.CreateApplicationConfiguration(httpClient);

            WebAssemblyHostBuilderExtensions.ConfigureServices(services, appConfiguration, appConfiguration.Get <Settings>());

            Services.GetRequiredService <TestUserService>()
            .SetTestUser(true, claims.Select(c => new Claim(c.Type, c.Value)));

            services.AddTransient(p => Server.CreateHandler())
            .AddAdminHttpStores(p =>
            {
                var client = new HttpClient(new BaseAddressAuthorizationMessageHandler(p.GetRequiredService <IAccessTokenProvider>(),
                                                                                       p.GetRequiredService <NavigationManager>())
                {
                    InnerHandler = Server.CreateHandler()
                })
                {
                    BaseAddress = new Uri(httpClient.BaseAddress ?? new Uri(string.Empty), "api")
                };
                return(Task.FromResult(client));
            })
            .AddScoped(p => new Settings
            {
                ApiBaseUrl       = appConfiguration["ApiBaseUrl"],
                WelcomeContenUrl = $"{httpClient.BaseAddress}api/welcomefragment"
            })
            .AddScoped(p => localizerMock.Object)
            .AddScoped(p => localizerMock)
            .AddTransient(p => new HttpClient(Server.CreateHandler()))
            .AddTransient <BaseAddressAuthorizationMessageHandler>()
            .AddScoped <SignOutSessionStateManager, TestUtils.FakeSignOutSessionStateManager>()
            .AddSingleton <IAccessTokenProviderAccessor, TestUtils.AccessTokenProviderAccessor>()
            .AddScoped <IAccessTokenProvider>(p => p.GetRequiredService <TestUtils.FakeAuthenticationStateProvider>())
            .AddScoped <AuthenticationStateProvider>(p => p.GetRequiredService <TestUtils.FakeAuthenticationStateProvider>())
            .AddScoped(p => new TestUtils.FakeAuthenticationStateProvider(
                           userName,
                           claims))
            .AddScoped <LazyAssemblyLoader>()
            .AddHttpClient("oidc")
            .ConfigureHttpClient(httpClient =>
            {
                var apiUri             = new Uri(httpClient.BaseAddress ?? new Uri(string.Empty), "api");
                httpClient.BaseAddress = apiUri;
            })
            .AddHttpMessageHandler(() => new TestUtils.FakeDelegatingHandler(Server.CreateHandler()));

            services.AddHttpClient(nameof(ConfigurationService))
            .AddHttpMessageHandler(() => new TestUtils.FakeDelegatingHandler(Server.CreateHandler()));
        }
Пример #5
0
        private static void NavigateToLoginPage(TestLoggerProvider testLoggerProvider, TestServer server, IServiceScope scope, ConcurrentDictionary <object, object> sessionStore, out HttpClient httpClient, out string redirectUri)
        {
            SeedData.SeedUsers(scope);
            SeedData.SeedConfiguration(scope);

            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: "http://exemple.com");

            var client = server.CreateClient();

            httpClient = client;

            host.ConfigureServices(services =>
            {
                var configuration = TestUtils.CreateApplicationConfiguration(client);
                WebAssemblyHostBuilderExtensions.ConfigureServices(services, configuration, configuration.Get <Settings>(), client.BaseAddress.ToString());
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(client))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);
            jsRuntimeMock.Setup(m => m.InvokeAsync <object>("sessionStorage.setItem", It.IsAny <object[]>()))
            .Callback <string, object[]>((_, array) => sessionStore.AddOrUpdate(array[0], array[1], (k, v) => array[1]))
            .ReturnsAsync(null);

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });

            host.WaitForContains(component, "You are redirecting to the login page. please wait");

            WaitForHttpResponse(waitHandle);

            redirectUri = navigatedUri;
        }
Пример #6
0
        private static void OpenLogggedPage(TestLoggerProvider testLoggerProvider, HttpClient httpClient, ConcurrentDictionary <object, object> sessionStore, string location)
        {
            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: location);

            host.ConfigureServices(services =>
            {
                var configuration = TestUtils.CreateApplicationConfiguration(httpClient);
                WebAssemblyHostBuilderExtensions.ConfigureServices(services, configuration, configuration.Get <Settings>(), httpClient.BaseAddress.ToString());
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(httpClient))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);

            foreach (var key in sessionStore.Keys)
            {
                jsRuntimeMock.Setup(m => m.InvokeAsync <string>("sessionStorage.getItem", It.Is <object[]>(p => p[0].ToString() == key.ToString())))
                .ReturnsAsync <string, object[], IJSRuntime, string>((_, array) =>
                {
                    if (sessionStore.TryGetValue(array[0], out object value))
                    {
                        return((string)value);
                    }
                    throw new InvalidOperationException($"sessionStore doesn't contain key {key}");
                });
            }

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });


            WaitForHttpResponse(waitHandle);

            Assert.Equal("http://exemple.com", navigatedUri);
        }