Search code examples
c#asp.net-coreasp.net-web-apioauth-2.0oauth

Access OAuth2 endpoint from an ASP.NET Core Web API application


I have a ASP.NET Core Web API application, and this web API needs to call another 3rd-party API which is authenticated using OAuth2. It is required to invoke the /token endpoint of this 3rd-party API by passing client_id and client_secret, and the grant type is client_credentials. And then make a subsequent request using the bearer token received to retrieve data from the 3rd-party API .

Based on my research this requirement can be implemented using HttpClient, and call 3rd-party API from the .NET Core Web API controller (or ideally in a service class accessed by the controller).

My question is is there another way/better approach to achieve this requirement? One concern I have in above approach is it will call the 3rd-party /token endpoint for each request. Is it possible to do some implementation in Startup.cs class?


Solution

  • Take a look at IdentityModel. It provides extension methods for HttpClient to handle client_credentials (and other) OAuth flow, caches the token (until it expires), so you don't hammer /token endpoint at every request and refreshes the token when needed.

    You need to configure it in your Startup class, or implement ITokenClientConfigurationService if you need configure HttpClients dynamically.

    services.AddAccessTokenManagement(options =>
    {
        options.Client.Clients.Add("identityserver", new ClientCredentialsTokenRequest
        {
            Address = "https://demo.identityserver.io/connect/token",
            ClientId = "m2m.short",
            ClientSecret = "secret",
            Scope = "api" // optional
        });
    });