public async Task OAuthHttpHandler_WithHttpClientFactory_OmittedExplicitInnerHandler_ShouldReturnOk()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri(_server.BaseAddress, "/connect/authorize"),
                    TokenEndpointUrl     = new Uri(_server.BaseAddress, "/connect/token"),
                    ClientId             = "MyId",
                    ClientSecret         = "MySecret",
                    GrantType            = GrantType.ClientCredentials,
                    Scope = new[] { "test" }
                }
            };

            var services = new ServiceCollection();

            services
            .AddHttpClient("test")
            .AddHttpMessageHandler(_ => new OAuthHttpHandler(options, () => new HttpClient(_handler, false)))
            .ConfigurePrimaryHttpMessageHandler(() => _handler);

            using (var client = services.BuildServiceProvider().GetRequiredService <IHttpClientFactory>().CreateClient("test"))
            {
                client.BaseAddress = _server.BaseAddress;
                var response = await client.GetAsync("/api/authorize");

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
        public void OAuthHttpHandler_InvalidClientCredentialsWithoutOnErrorCallback_ShouldThrowProtocolException()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri("http://localhost/authorizer"),
                    TokenEndpointUrl = new Uri("http://localhost/token"),
                    ClientId = "WrongId",
                    ClientSecret = "WrongSecret",
                    GrantType = GrantType.ClientCredentials
                },
                InnerHandler = server.Handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = new Uri("http://localhost");
                var ex = Assert.Throws<ProtocolException>(async () => await client.GetAsync("/api/authorize"));
                Assert.AreEqual(HttpStatusCode.BadRequest, ex.StatusCode);
            }
        }
        public async Task OAuthHttpHandler_ValidClientCredentials_ShouldReturnOk()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri("http://localhost/authorizer"),
                    TokenEndpointUrl = new Uri("http://localhost/token"),
                    ClientId = "MyId",
                    ClientSecret = "MySecret",
                    GrantType = GrantType.ClientCredentials
                },
                InnerHandler = server.Handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = new Uri("http://localhost");
                var response = await client.GetAsync("/api/authorize");
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
        public void OAuthHttpHandler_InvalidClientCredentialsWithoutOnErrorCallback_ShouldThrowProtocolException()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri(_server.BaseAddress, "/connect/authorize"),
                    TokenEndpointUrl     = new Uri(_server.BaseAddress, "/connect/token"),
                    ClientId             = "WrongId",
                    ClientSecret         = "WrongSecret",
                    GrantType            = GrantType.ClientCredentials
                },
                InnerHandler = _handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = _server.BaseAddress;
                var ex = Assert.ThrowsAsync <ProtocolException>(async() => await client.GetAsync("/api/authorize"));
                Assert.AreEqual(HttpStatusCode.BadRequest, ex.StatusCode);
            }
        }
Esempio n. 5
0
        public static IMyPontoApi Create(string clientId, string clientSecret, int pageSize = 100, string pontoEndpoint = "https://api.myponto.com")
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    TokenEndpointUrl = new Uri($"{pontoEndpoint}/oauth2/token"),
                    ClientId         = clientId,
                    ClientSecret     = clientSecret,
                    GrantType        = GrantType.ClientCredentials
                }
            };
            var httpClient = new HttpClient(new OAuthHttpHandler(options));

            httpClient.BaseAddress = new Uri(pontoEndpoint);
            var pontoClient = new MyPontoApi();

            pontoClient.Accounts         = new AccountApi(httpClient, pageSize, pontoClient);
            pontoClient.Synchronizations = new SynchronizationApi(httpClient, pageSize, pontoClient);
            pontoClient.Transactions     = new TransactionApi(httpClient, pageSize, pontoClient);
            return(pontoClient);
        }
        public async Task OAuthHttpHandler_UnauthorizedRequest_ShouldReturnForbidden()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri(_server.BaseAddress, "/connect/authorize"),
                    TokenEndpointUrl     = new Uri(_server.BaseAddress, "/connect/token"),
                    ClientId             = "MyId",
                    ClientSecret         = "MySecret",
                    GrantType            = GrantType.ClientCredentials
                },
                InnerHandler = _handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = _server.BaseAddress;
                var response = await client.GetAsync("/api/unauthorized");

                Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
            }
        }
        public async Task OAuthHttpHandler_ValidClientCredentials_ShouldReturnOk()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri("http://localhost/authorizer"),
                    TokenEndpointUrl     = new Uri("http://localhost/token"),
                    ClientId             = "MyId",
                    ClientSecret         = "MySecret",
                    GrantType            = GrantType.ClientCredentials
                },
                InnerHandler = Handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = new Uri("http://localhost");
                var response = await client.GetAsync("/api/authorize");

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
        public async Task OAuthHttpHandler_InvalidClientCredentialsWithOnErrorCallback_ShouldReturnUnauthorized()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri(_server.BaseAddress, "/connect/authorize"),
                    TokenEndpointUrl     = new Uri(_server.BaseAddress, "/connect/token"),
                    ClientId             = "WrongId",
                    ClientSecret         = "WrongSecret",
                    GrantType            = GrantType.ClientCredentials,
                    OnError = (statusCode, message) => { }
                },
                InnerHandler = _handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = _server.BaseAddress;
                var response = await client.GetAsync("/api/authorize");

                Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            }
        }
        public void OAuthHttpHandler_WithHttpClientFactory_ExplicitInnerHandler_ShouldFail()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri(_server.BaseAddress, "/connect/authorize"),
                    TokenEndpointUrl     = new Uri(_server.BaseAddress, "/connect/token"),
                    ClientId             = "MyId",
                    ClientSecret         = "MySecret",
                    GrantType            = GrantType.ClientCredentials,
                    Scope = new[] { "test" }
                },
                InnerHandler = _handler
            };

            var services = new ServiceCollection();

            services
            .AddHttpClient("test")
            .AddHttpMessageHandler(_ => new OAuthHttpHandler(options));

            Assert.Throws <InvalidOperationException>(() => services.BuildServiceProvider().GetRequiredService <IHttpClientFactory>().CreateClient("test"));
        }
        public async Task OAuthHttpHandler_InvalidClientCredentialsWithOnErrorCallback_ShouldReturnUnauthorized()
        {
            var options = new OAuthHttpHandlerOptions
            {
                AuthorizerOptions = new AuthorizerOptions
                {
                    AuthorizeEndpointUrl = new Uri("http://localhost/authorizer"),
                    TokenEndpointUrl = new Uri("http://localhost/token"),
                    ClientId = "WrongId",
                    ClientSecret = "WrongSecret",
                    GrantType = GrantType.ClientCredentials,
                    OnError = (statusCode, message) => { }
                },
                InnerHandler = server.Handler
            };

            using (var client = new HttpClient(new OAuthHttpHandler(options)))
            {
                client.BaseAddress = new Uri("http://localhost");
                var response = await client.GetAsync("/api/authorize");
                Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            }
        }
Esempio n. 11
0
        public static int Main(string[] args)
        {
            int errorCode = 0;

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                if (String.IsNullOrEmpty(o.Password))
                {
                    o.Password = SecureStringToString(GetPasswordFromConsole("Password: "******"{0}/v2/info", o.ApiEndpoint)).Result;
                    infoResponse = DeserializeJson <GetInfoResponse>(response.Content.ReadAsStringAsync().Result);
                }

                var options = new OAuthHttpHandlerOptions
                {
                    AuthorizerOptions = new AuthorizerOptions
                    {
                        AuthorizeEndpointUrl      = new Uri(infoResponse.AuthorizationEndpoint),
                        TokenEndpointUrl          = new Uri(String.Format("{0}/oauth/token", infoResponse.TokenEndpoint)),
                        ClientId                  = "cf",
                        ClientSecret              = "",
                        Username                  = o.User,
                        Password                  = o.Password,
                        GrantType                 = GrantType.ResourceOwnerPasswordCredentials,
                        CredentialTransportMethod = CredentialTransportMethod.FormAuthenticationCredentials
                    }
                };

                List <Tuple <string, string, string, DateTime> > report = new List <Tuple <string, string, string, DateTime> >();

                using (var httpClient = new HttpClient(new OAuthHttpHandler(options)))
                {
                    var builder = new UriBuilder(String.Format("{0}/v2/events", o.ApiEndpoint));
                    using (var content = new FormUrlEncodedContent(new [] {
                        new KeyValuePair <string, string> ("q", "timestamp>=" + o.StartDate.ToUniversalTime().ToString(DateFormat)),
                        new KeyValuePair <string, string> ("q", "timestamp<" + o.EndDate.ToUniversalTime().ToString(DateFormat)),
                        new KeyValuePair <string, string> ("q", "type:audit.app.build.create"),
                    })) {
                        builder.Query = content.ReadAsStringAsync().Result;
                    }

                    PagedResponse <Event> pagedResponse = DeserializeJson <PagedResponse <Event> >(httpClient.GetAsync(builder.ToString()).Result.Content.ReadAsStringAsync().Result);

                    while (pagedResponse != null && pagedResponse.TotalResults != 0)
                    {
                        foreach (var resource in pagedResponse.Resources)
                        {
                            report.Add(
                                Tuple.Create(
                                    GetOrgNameForGuid(httpClient, o.ApiEndpoint, resource.Entity.OrganizationGuid),
                                    GetSpaceNameForGuid(httpClient, o.ApiEndpoint, resource.Entity.SpaceGuid),
                                    resource.Entity.ActeeName,
                                    resource.Entity.Timestamp
                                    )
                                );
                        }
                        if (pagedResponse.NextUrl != null)
                        {
                            pagedResponse = DeserializeJson <PagedResponse <Event> >(httpClient.GetAsync(o.ApiEndpoint + pagedResponse.NextUrl).Result.Content.ReadAsStringAsync().Result);
                        }
                        else
                        {
                            pagedResponse = null;
                        }
                    }
                }

                OutputReport(report);
            });

            return(errorCode);
        }