SkillAgentSearch skills...

Geko.HttpClientService

An easy way to make HTTP requests to JSON endpoints, with IdentityServer4 integration.

Install / Use

/learn @georgekosmidis/Geko.HttpClientService
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

An easy way to make HTTP requests to JSON endpoints, with IdentityServer4 integration

Build Status Nuget

An almost 2x times faster fluent HTTP request service, build to simplify the communication with JSON endpoints, by automatically handling serialization / deserialization. Authenticated requests towards protected by IdentityServer4 resources are done in a simple compact way.

Add it to the service collection in Startup.cs

  services.AddHttpClientService();
  
  //Or if the resources are behind an IdentityServer4
  services.AddHttpClientService(
          .Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));

Calls can be easy as that :)

var responseObject = await _requestServiceFactory
 //Create a instance of the service
 .CreateHttpClientService()
 //GET and deserialize the response body to IEnumerable<Customers>
 .GetAsync<IEnumerable<Customers>>("https://api/customers");

Check the Getting started guide for more details!


Table of Contents

  1. Getting started
    1. It’s a nuget package!
    2. IdentityServer4 Access Token Request Options
    3. Register the service
    4. You are done!
  2. How to setup an Access Token Request
    1. .SetIdentityServerOptions<TOptions>(TOptions)
    2. .SetIdentityServerOptions<TOptions>(IOptions<TOptions>)
    3. .SetIdentityServerOptions<TOptions>(Action<TOptions>)
  3. More info on how to serialize request, deserialize response
    1. ResponseObject
    2. TypeContent(TRequestBody, Encoding, string)
  4. Configuring the colleration id
  5. Contributing

Getting started

Getting started with Geko.HttpClientService is rather easy, since you only need three things:

  1. Install the nuget package Geko.HttpClientService
  2. Optionally, provide the options to request an access token from an IdentityServer4 service in the appsettings.json
  3. Register the service in Startup.cs

It's a nuget package

Install the Geko.HttpClientService nuget package, using any of your favorite ways.

Optionally, set the IdentityServer4 Access Token Request Options

Add the IdentityServer4 Access Token Request Options to your appsettings.json (the configuration section should always be or end with ClientCredentialsOptions):

"ClientCredentialsOptions": {
    "Address": "https://demo.identityserver.io/connect/token",
    "ClientId": "m2m",
    "ClientSecret": "secret",
    "Scope": "api"
}
 // The values above are part of the demo offered in https://demo.identityserver.io/

Register the service

Register the service In StartUp.cs in ConfigureServices(IServiceCollection services):

services.AddHttpClientService()
        //Optional, set it if you have ClientCredentialsOptions or PasswordOptions
        .Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));

You are done

Request the IHttpClientServiceFactory wherever you want to make the authenticated requests:

using Geko.HttpClientService.Extensions;

[ApiController]
[Route("customers")]
public class CustomerController : ControllerBase
{
 //Request the IHttpClientServiceFactory instance in your controller or service
 private readonly IHttpClientServiceFactory _requestServiceFactory;
 public CustomerController(IHttpClientServiceFactory requestServiceFactory){
  _requestServiceFactory = requestServiceFactory;
 }

 [HttpGet]
 public async Task<IActionResult> Get(){
  //Make the request
  var responseObject = await _requestServiceFactory
   //Create a instance of the service
   .CreateHttpClientService()
   //GET and deserialize the response body to IEnumerable<Customers>
   .GetAsync<IEnumerable<Customers>>("https://api/customers");

  //Do something with the results       
  if (!responseObject.HasError)
  {
   var customers = responseObject.BodyAsType;
   return Ok(customers);
  }
  else
  {
   var httpStatusCode = responseObject.StatusCode;
   var errorMessage = responseObject.Error;           
   return StatusCode((int)httpStatusCode, errorMessage);
  }
 }
} 

Configuring the service from startup following the Options Pattern is the simpler way, but there are more ways HTTP verbs supported are: GET, POST, PUT, DELETE, PATCH and HEAD.

Wanna study more?

You can also take a look at the Documentation for technical details, check the features sample or a more complete one.


How to setup an Access Token Request

The library supports multiple ways for setting up the necessary options for retrieving an access token. Upon success of retrieving one, the result is cached until the token expires; that means that a new request to a protected resource does not necessarily means a new request for an access token.

Currently, the library only supports ClientCredentialsTokenRequest and PasswordTokenRequest.

.SetIdentityServerOptions<TOptions>(TOptions)

Setup IdentityServer options by passing a ClientCredentialsOptions or PasswordOptions directly to the SetIdentityServerOptions:

//...
.SetIdentityServerOptions(
  new PasswordOptions
  {
    Address = "https://demo.identityserver.io/connect/token",
    ClientId = "ClientId",
    ClientSecret = "ClientSecret",
    Scope = "Scope",
    Username = "Username",
    Password = "Password"
  }
)
//...

.SetIdentityServerOptions<TOptions>(IOptions<TOptions>)

Setup IdentityServer options using the options pattern (read more about the options pattern in Microsoft Docs):

Startup.cs

//...
    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddHttpClientService()
            .AddSingleton<IProtectedResourceService, ProtectedResourceService>()
            .Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));    
        //...
    }
//...

ProtectedResourceService.cs

//...
public class ProtectedResourceService : IProtectedResourceService
{
  private readonly IHttpClientServiceFactory _requestServiceFactory;
  private readonly IOptions<ClientCredentialsOptions> _identityServerOptions;

  public ProtectedResourceService(IHttpClientServiceFactory requestServiceFactory, IOptions<ClientCredentialsOptions> identityServerOptions)
  {
    _requestServiceFactory = requestServiceFactory;
    _identityServerOptions = identityServerOptions;
  }

  public async Task<YourObject> Get(){
    _requestServiceFactory
    .CreateHttpClientService()
    .SetIdentityServerOptions(_identityServerOptions)
    .GetAsync<YourObject>("https://url_that_returns_YourObject");
  }
)
//...

.SetIdentityServerOptions<TOptions>(Action<TOptions>)

Setup IdentityServer options using a delegate:

//...
.SetIdentityServerOptions<PasswordOptions>( x => {
    x.Address = "https://demo.identityserver.io/connect/token";
    x.ClientId = "ClientId";
    x.ClientSecret = "ClientSecret";
    x.Scope = "Scope";
    x.Username = "Username";
    x.Password = "Password";
  }
)
//...

More info on how to serialize request, deserialize response

Responses can always be deserialized to the type TResponseBody with GetAsync<TResponseBody>:

//...
.GetAsync<ResponsePoco>("https://url_that_returns_ResponsePoco_in_json");
//...

Using a complex type as a request body for POST, PUT and PATCH requests is also very easy. In the example that follows the type TRequestBody of the PostAsync<TRequestBody,TResponseBody> sets the type of the requestPoco object. This will be serialized using JsonConvert.SerializeObject(requestPoco, Formatting.None):

//...
.PostAsync<RequestP

Related Skills

View on GitHub
GitHub Stars7
CategoryDevelopment
Updated3y ago
Forks3

Languages

C#

Security Score

75/100

Audited on Dec 11, 2022

No findings