private static async Task TestOAuth2() { // discover endpoints from metadata var client = new System.Net.Http.HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } // request token var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "client", ClientSecret = "secret", Scope = "api1" }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } Console.WriteLine(tokenResponse.Json); Console.WriteLine("\n\n"); // call api var apiClient = new System.Net.Http.HttpClient(); apiClient.SetBearerToken(tokenResponse.AccessToken); var response = await apiClient.GetAsync("https://localhost:6001/identity"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); var data = System.Text.Json.JsonSerializer.Deserialize <dynamic>(content); Console.WriteLine(data); } }
public async Task <IEnumerable <WeatherForecast> > Get() { var OAuth2Token = await _identityServer4Service.GetToken("weatherApi.read"); using (var client = new System.Net.Http.HttpClient()) { client.SetBearerToken(OAuth2Token.AccessToken); var result = await client.GetAsync("https://localhost:44332/weatherforecast"); if (result.IsSuccessStatusCode) { var model = await result.Content.ReadAsStringAsync(); return(System.Text.Json.JsonSerializer.Deserialize <List <WeatherForecast> >(model)); } else { throw new Exception("Some Error while fetching Data"); } } }