Example #1
0
        public async Task CanUseImplicitClient()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id   = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name = $"{nameof(ClientManagement)}.{nameof(this.CanUseImplicitClient)} (integration test)",
                AllowedCorsOrigins          = { "http://localhost:5006" },
                RedirectUris                = { "http://localhost:5006/redirect" },
                AllowedScopes               = { "openid", "profile", "sample_api" },
                AllowAccessTokensViaBrowser = true,
                AllowedGrantTypes           = { "implicit" },
                RequireConsent              = false,
            };

            await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // act
            var url = new RequestUrl(this.Authority + "/connect/authorize")
                      .CreateAuthorizeUrl(client.Id, "id_token token", "openid profile sample_api", client.RedirectUris.First(), "state", "nonce");

            var automation = new BrowserAutomation("admin", "password");
            await automation.NavigateToLoginAsync(url).ConfigureAwait(false);

            var authorizeResponse = await automation.LoginToAuthorizationServerAndCaptureRedirectAsync().ConfigureAwait(false);

            // assert
            authorizeResponse.IsError.Should().BeFalse();
        }
Example #2
0
        public async Task CanAddClient()
        {
            // arrange
            var httpClient     = new ClientsHttpClient(this.Authority, this.Handler);
            var expectedClient = new Client
            {
                Id                          = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name                        = $"{nameof(ClientManagement)}.{nameof(this.CanAddClient)} (integration test)",
                Secret                      = "secret",
                AllowedCorsOrigins          = { "http://localhost:5005" },
                RedirectUris                = { "http://localhost:5005/redirect" },
                PostLogoutRedirectUris      = { "http://localhost:5005/post-logout-redirect" },
                AllowedScopes               = { "role", "name" },
                AccessTokenType             = "Reference",
                AllowedGrantTypes           = { "implicit", "custom" },
                AllowAccessTokensViaBrowser = true,
                AllowOfflineAccess          = true,
                RequireClientSecret         = false,
                RequirePkce                 = true,
                RequireConsent              = false,
                Enabled                     = false,
            };

            // act
            await httpClient.AddClientAsync(expectedClient).ConfigureAwait(false);

            // assert
            var actualClient = await httpClient.GetClientAsync(expectedClient.Id).ConfigureAwait(false);

            actualClient.Should().NotBeNull();
            actualClient.Should().BeEquivalentTo(expectedClient, options => options.Excluding(client => client.Secret));
        }
Example #3
0
        public async Task CanGetClientSummariesWithQuery()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client1    = new Client {
                Id = "query"
            };
            var client2 = new Client {
                Id = "query_test_02"
            };
            var client3 = new Client {
                Id = "query_test_03"
            };

            await httpClient.AddClientAsync(client1).ConfigureAwait(false);

            await httpClient.AddClientAsync(client2).ConfigureAwait(false);

            await httpClient.AddClientAsync(client3).ConfigureAwait(false);

            // act
            var clientSummaries = await httpClient.GetClientSummariesAsync("query_").ConfigureAwait(false);

            // assert
            clientSummaries.Should().NotBeNull();
            clientSummaries.Should().HaveCount(2);
            clientSummaries.Should().Contain(summary => summary.Id == client2.Id);
            clientSummaries.Should().Contain(summary => summary.Id == client3.Id);
        }
Example #4
0
        public void CannotRemoveAuthorizationServerManagementConsole()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var clientId   = "auth_console";

            // act
            Func <Task> func = async() => await httpClient.RemoveClientAsync(clientId).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>().And.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Example #5
0
        public void CannotModifyAuthorizationServerManagementConsole()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id            = "auth_console",
                AllowedScopes = { "openid" },
            };

            // act
            Func <Task> func = async() => await httpClient.ModifyClientAsync(client).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>().And.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Example #6
0
        public void CannotAddInvalidClient()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                AccessTokenType = "Nonsense",
            };

            // act
            Func <Task> func = async() => await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>();
        }
Example #7
0
        public async Task CannotAddDuplicateClient()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id   = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name = $"{nameof(ClientManagement)}.{nameof(this.CannotAddDuplicateClient)} (integration test)",
            };

            await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // act
            Func <Task> func = async() => await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>().And.StatusCode.Should().Be(HttpStatusCode.Conflict);
        }
Example #8
0
        public async Task CanAddClientMinimum()
        {
            // arrange
            var httpClient     = new ClientsHttpClient(this.Authority, this.Handler);
            var expectedClient = new Client
            {
                Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
            };

            // act
            await httpClient.AddClientAsync(expectedClient).ConfigureAwait(false);

            // assert
            var actualClient = await httpClient.GetClientAsync(expectedClient.Id).ConfigureAwait(false);

            actualClient.Should().NotBeNull();
            actualClient.Id.Should().Be(expectedClient.Id);
        }
Example #9
0
        public async Task CanGetClientSummaries()
        {
            // arrange
            var httpClient     = new ClientsHttpClient(this.Authority, this.Handler);
            var expectedClient = new Client
            {
                Id   = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name = $"{nameof(ClientManagement)}.{nameof(this.CanGetClientSummaries)} (integration test)",
            };

            await httpClient.AddClientAsync(expectedClient).ConfigureAwait(false);

            // act
            var clientSummaries = await httpClient.GetClientSummariesAsync().ConfigureAwait(false);

            // assert
            clientSummaries.Should().NotBeNull();
            clientSummaries.Should().Contain(summary => summary.Id == expectedClient.Id && summary.Name == expectedClient.Name);
        }
Example #10
0
        public async Task CanUseHybridClient()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id   = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name = $"{nameof(ClientManagement)}.{nameof(this.CanUseHybridClient)} (integration test)",
                RequireClientSecret = false,
                AllowedGrantTypes   = { "hybrid" },
                RequirePkce         = true,
                RedirectUris        = { "http://127.0.0.1" },
                AllowOfflineAccess  = true,
                AllowedScopes       = { "openid", "profile", "sample_api" },
                RequireConsent      = false,
            };

            await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // act
            var automation = new BrowserAutomation("admin", "password");
            var browser    = new Browser(automation);
            var options    = new OidcClientOptions
            {
                Authority    = this.Authority,
                ClientId     = client.Id,
                RedirectUri  = $"http://127.0.0.1:{browser.Port}",
                Scope        = "openid profile sample_api offline_access",
                FilterClaims = false,
                Browser      = browser,
                Policy       = new Policy {
                    Discovery = new DiscoveryPolicy {
                        ValidateIssuerName = false
                    }
                }
            };

            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.LoginAsync(new LoginRequest()).ConfigureAwait(false);

            // assert
            result.IsError.Should().BeFalse();
        }
Example #11
0
        public async Task CanUseClientCredentialsClient()
        {
            // arrange
            var httpClient = new ClientsHttpClient(this.Authority, this.Handler);
            var client     = new Client
            {
                Id                = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Name              = $"{nameof(ClientManagement)}.{nameof(this.CanUseClientCredentialsClient)} (integration test)",
                Secret            = "secret",
                AllowedScopes     = { "sample_api" },
                AllowedGrantTypes = { "client_credentials" },
            };

            await httpClient.AddClientAsync(client).ConfigureAwait(false);

            // act
            var tokenClient = new TokenClient(this.Authority + "/connect/token", client.Id, client.Secret);
            var response    = await tokenClient.RequestClientCredentialsAsync("sample_api").ConfigureAwait(false);

            // assert
            response.IsError.Should().BeFalse();
        }
Example #12
0
        public async Task <int> TryRunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, this.console);
            }
            catch (CommandParsingException ex)
            {
                new ConsoleReporter(this.console).Warn(ex.Message);
                return(1);
            }

            if (options == null)
            {
                return(1);
            }

            if (options.Help.HasValue())
            {
                return(2);
            }

            if (options.Command == null)
            {
                return(3);
            }

            var repository = new CommandDataRepository(this.provider);

            if (options.Command is LoginCommand.Reset)
            {
                await options.Command.ExecuteAsync(new CommandContext(this.console, null, null, null, null, null, null, repository)).ConfigureAwait(false);

                return(0);
            }

            var data = repository.GetCommandData() ??
                       new CommandData
            {
                Authority = LoginCommand.ProductionAuthority,
            };

            var authority = data.Authority;

            if (options.Command is LoginCommand loginCommand)
            {
                authority = loginCommand.Authority;
            }
            else
            {
                this.console.Write("Executing command against ");
                this.console.ForegroundColor = ConsoleColor.White;
                this.console.Write(authority);
                this.console.ResetColor();
                this.console.WriteLine("...");
            }

            var discoveryResponse = default(DiscoveryResponse);

            using (var discoveryClient = new DiscoveryClient(authority))
            {
                discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                if (discoveryResponse.IsError)
                {
                    await this.console.Error.WriteLineAsync(discoveryResponse.Error).ConfigureAwait(false);

                    return(500);
                }
            }

            using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "auth_console"))
                using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                    using (var clientsClient = new ClientsHttpClient(authority, refreshTokenHandler))
                        using (var apiResourcesClient = new ApiResourcesHttpClient(authority, refreshTokenHandler))
                            using (var identityResourcesClient = new IdentityResourcesHttpClient(authority, refreshTokenHandler))
                                using (var rolesClient = new RolesHttpClient(authority, refreshTokenHandler))
                                    using (var usersClient = new UsersHttpClient(authority, refreshTokenHandler))
                                    {
                                        refreshTokenHandler.TokenRefreshed += (sender, e) =>
                                        {
                                            repository.SetCommandData(
                                                new CommandData
                                            {
                                                Authority    = authority,
                                                AccessToken  = e.AccessToken,
                                                RefreshToken = e.RefreshToken,
                                            });
                                        };

                                        var reporter = new ConsoleReporter(this.console, options.Verbose.HasValue(), false);
                                        var context  = new CommandContext(this.console, reporter, clientsClient, apiResourcesClient, identityResourcesClient, rolesClient, usersClient, repository);

                                        try
                                        {
                                            await options.Command.ExecuteAsync(context).ConfigureAwait(false);
                                        }
                                        catch (Exception ex)
                                        {
                                            reporter.Error(ex.Message);
                                            return(500);
                                        }
                                        finally
                                        {
                                            this.console.ResetColor();
                                        }

                                        return(0);
                                    }
        }