Skip to main content

IdentityServer4 Protecting Web API Using Client Credentials - Implement IClientStore And IResourceStore

In this article, we will implement an IdentityServer4 to protect a Web API with client credentials.

Client Credentials Flow:

Client credential flow suitable internal communication between that application. In this flow application request the IdentityServer jwt access token to consume the protected API resources.

  • Client Credential flow requires 'ClientId', 'ClientSecret' for authentication.
  • Clients are applications that want to consume the protected API by the IdentiyServer.
  • Each client should register with IdentiyServer. So IdentityServer stores client information like 'ClientId'(unique identifier), 'ClientSecrets', 'Scopes' etc.
  • So clients using 'ClientId', 'ClientSecret', 'Scopes'(optional) can request the IdentityServer as a trust client to get the JWT token.
  • Protected API's are registered under IdentityServer as 'ApiResoucers' with set of 'Scopes'.
  • So any client to access the protected API, then client scopes should match with scopes of the 'ApiResource'.
  • The Jwt token contains those scope information that can be used by protected API as Authorization claim value.

IClientStore And IResourceStore:

IdentityServer provides clients of type 'IdentityServer4.Models.Client'. This client type contains properties to configure our clients. If our IdentityServer application is used by very very few client applications then we can write all configurations inside some static method and then register with the 'AddInMemoryClients()' method in the 'Startup.cs'. But if we have more number of clients depends on our IdentiyServer then it's an obvious good choice to load them from the database. So to retrieve from the database we have to implement the 'IClientStore' and then register with the 'AddClientStore<T>'.

To protect API we have to maintain scopes at the IdentiyServer. IdentiyServer provides scope type like 'IdentityServer4.Models.ApiScope', 'IdentiyServer4.Models.ApiResoruce'. Either we can register scopes only using 'IdentityServer4.Models.ApiScope' or using both. So if we have only a few API's to protect then we can write all configuration inside of some static method and then register with the 'AddInMemoryApiScopes()' method, if we use 'ApiResource' then need to register one more additional method like 'AddInMemoryApiResources()' methods in the 'Startup.cs'. But if we have more APIs to protect then it's obviously a good choice to load them from the database. So to retrieve from the database we have to implement the 'IResourceStore' and then register with the 'AddResourceStore<T>'.

Database Design:


  • Here is a small overview of the table structure of our IdentityServer for Client Credentials authentication flow.
  • In a fully developed IdentityServer application 'Client' table has a lot of child tables. Here we are creating few child tables that support for Client Credentials authentication. So our child tables are like 'ClientGrantTypes', 'ClientScopes', 'ClientSecrets'.
  • The 'ApiResources' table and its child table like 'ApiResourceScopes'.

Database Scripts:

The 'Client' table scripts.
CREATE TABLE Client(
Id INT IDENTITY(1,1) NOT NULL,
ClientId VARCHAR(300),
ClientName VARCHAR(300)
CONSTRAINT Pk_Client PRIMARY KEY (Id)
)
Command to insert test data into the 'Client' table.
INSERT INTO Client Values('MyClient', 'My Client')
The 'ClientGrantTypes' table scripts.
CREATE TABLE ClientGrantTypes(
Id INT IDENTITY(1,1) NOT NULL,
ClientId INT NOT NULL,
GrantType VARCHAR(300)
CONSTRAINT Pk_ClientGrantTypes PRIMARY KEY (Id)
)
Command to insert test data into the 'ClientGrantTypes' table.
INSERT INTO ClientGrantTypes Values(1, 'client_credentials')
The 'ClientSecrets' table scripts.
CREATE TABLE ClientSecrets(
Id INT IDENTITY(1,1) NOT NULL,
ClientId INT NOT NULL,
Secrets VARCHAR(300)
CONSTRAINT Pk_ClientSecrets PRIMARY KEY (Id)
)
Command to insert test data into the 'ClientSecrets' table.
INSERT INTO ClientSecrets Values(1, 'MySecrets')
The 'ClientScopes' table scripts.
CREATE TABLE ClientScopes(
Id INT IDENTITY(1,1) NOT NULL,
ClientId INT NOT NULL,
Scope VARCHAR(300)
CONSTRAINT Pk_ClientScopes PRIMARY KEY (Id)
)
Command to insert test data into the 'ClientScopes' table.
INSERT INTO ClientScopes Values(1, 'API1.read')
The 'ApiResources' table scripts.
CREATE TABLE ApiResources(
Id INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(300),
DisplayName VARCHAR(300)
CONSTRAINT Pk_ApiResources PRIMARY KEY (Id)
)
Command to insert test data into the 'ApiResource' table.
INSERT INTO ApiResources Values('API1', 'Api 1')
The 'ApiResourceScopes' table scripts.
CREATE TABLE ApiResourceScopes(
Id INT IDENTITY(1,1) NOT NULL,
Scope VARCHAR(300),
ApiResourceId INT
CONSTRAINT Pk_ApiResourceScopes PRIMARY KEY (Id)
)
Command to insert test data into the 'ApiResourceScopes' table.
INSERT INTO ApiResourceScopes Values('API1.read', '1')

Create IdentityServer4 Application:

Let's begin coding by creating the IdneityServer4 application. For this demo I'm going to select the 'IdentityServer4 Empty' template.

Configure EfCore And Database Context:

Now let's install entity framework core and entity framework core SQL extension libraries.


Now let's create a new folder like 'Data', inside add another folder like 'Entities'. Inside the 'EntityFolder' let's add all our table classes.

Data/Entities/Client.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class Client
    {
        public int Id { get; set; }
        public string ClientId { get; set; }
        public string ClientName { get; set; }
    }
}
  • Here 'ClientId' is the unique identifier for the app that wants authentication with our IdentityServer application.
Data/Entites/ClientSecrets.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class ClientSecrets
    {
        public int Id { get; set; }
        public string Secrets { get; set; }
        public int ClientId { get; set; }
    }
}
  • The 'ClientSecrets' is the child table for the 'Client' table. A client can have multiple secrets.
Data/Entities/ClientGrantTypes.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class ClientGrantTypes
    {
        public int Id { get; set; }
        public string GrantType { get; set; }
        public int ClientId { get; set; }
    }
}
  • The 'ClientGrantTypes' is the child table for the 'Client' table. 
  • The 'GrantTypes' represents authentication type, so for our current demo is on Client Credentials then 'GranType' value is 'client_credentials'.
  •  A client can have different types of authentication techniques that mean the client can have different GrantTypes.
Data/Entities/ClientScopes.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class ClientScopes
    {
        public int Id { get; set; }
        public string Scope { get; set; }
        public int ClientId { get; set; }
    }
}
  • The 'ClientScopes' is the child table for the 'Client' table.
  • The 'Scope' value represents the permission to access the protected API by the client application.
Data/Entities/ApiResources.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class ApiResources
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayName { get; set; }

    }
}
  • The 'ApiResource' table is the lookup table that contains all the APIs protected by our IdentitySever. The 'Name' property value will be used in JWT token generation as 'aud' claim.
Data/Entities/ApiResourceScopes.cs:
namespace AuthDemo.IdentityServer4.App.Data.Entities
{
    public class ApiResourceScopes
    {
        public int Id { get; set; }
        public string Scope { get; set; }
        public int ApiResourceId { get; set; }
    }
}
  • The 'ApiResourceScopes' table is a child table for the 'ApiResources'. This table contains a collection of scopes for each protected API.
Let's implement DbContext into the 'Data' folder.
Data/AuthDbContext.cs:
using AuthDemo.IdentityServer4.App.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AuthDemo.IdentityServer4.App.Data
{
    public class AuthDbContext : DbContext
    {
        public AuthDbContext(DbContextOptions<AuthDbContext> options) : base(options)
        {

        }

        public DbSet<Client> Client { get; set; }
        public DbSet<ClientGrantTypes> ClientGrantTypes { get; set; }
        public DbSet<ClientSecrets> ClientSecrets { get; set; }
        public DbSet<ClientScopes> ClientScopes { get; set; }
        public DbSet<ApiResources> ApiResources { get; set; }
        public DbSet<ApiResourceScopes> ApiResourceScopes { get; set; }
    }
}
Create an 'appsettings.Development.json' file to load the connection string.
appsettings.Development.json:
"ConnectionStrings": {
    "AuthDbConnection": "your_connection"
}
Now register our 'AuthDbContext' in the 'Startup.cs'.
Startup.cs:
using AuthDemo.IdentityServer4.App.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

// existing code hidden for display purpose

namespace AuthDemo.IdentityServer4.App
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AuthDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("AuthDbConnection"));
            });
        }

        public void Configure(IApplicationBuilder app)
        {
        }
    }
}
  • (Line: 18) Inject 'IConfiguration', if it is not injected already.
  • (Line: 26-29) Registering the 'AuthDbContext'.

Implement IClientStore:

To load the client information from the database we have to implement the 'IClientStore'. Create a new folder like 'Core' and add a file like 'ClientStore.cs'.
Core/ClientStore.cs:
using AuthDemo.IdentityServer4.App.Data;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AuthDemo.IdentityServer4.App.Core
{
    public class ClientStore : IClientStore
    {
        private readonly AuthDbContext _authDbContext;
        public ClientStore(AuthDbContext authDbContext)
        {
            _authDbContext = authDbContext;
        }
        public async Task<Client> FindClientByIdAsync(string clientId)
        {

            var dbClient = await _authDbContext.Client.Where(_ => _.ClientId == clientId).FirstOrDefaultAsync();
            if(dbClient == null)
            {
                return new Client();
            }

            var dbClientGrantTypes = await _authDbContext.ClientGrantTypes.Where(_ => _.ClientId == dbClient.Id).ToListAsync();

            var dbclientSecrets = await _authDbContext.ClientSecrets.Where(_ => _.ClientId == dbClient.Id).ToListAsync();

            var dbClientScopes = await _authDbContext.ClientScopes.Where(_ => _.ClientId == dbClient.Id).ToListAsync();

            return new Client
            {
                ClientId = dbClient.ClientId,

                AllowedGrantTypes = (dbClientGrantTypes?.Count ?? 0) > 0 ?
                dbClientGrantTypes.Select(_ => _.GrantType).ToList() : new List<string>(),

                ClientSecrets = (dbclientSecrets?.Count ?? 0) > 0 ?
                dbclientSecrets.Select(_ => new Secret(_.Secret.Sha256())).ToList() : null,

                AllowedScopes = (dbClientScopes?.Count ?? 0) > 0?
                dbClientScopes.Select(_ => _.Scope).ToList(): new List<string>()
            };
        }
    }
}
  • (Line: 11) Implementing the 'IdentityServer4.Stores.IClient'.
  • (Line: 18) Implementing default a method like 'FindClientByIdAsync'. This method takes 'ClientId' as an input parameter which is provided from the request to IdentityServer.
  • (Line: 21) Fetching the 'Client' information by the 'ClientId'.
  • (Line: 22-25) Returning empty 'IdentiyServer4.Models.Client'
  • (Line: 27) Fetching the collection of 'ClientGrantTypes' by the 'ClientId'.
  • (Line: 29) Fetching the collection of 'ClientScretes' by the 'ClientId'.
  • (Line: 31) Fetching the collection of 'ClientScopes' by the 'ClientId'.
Now register our 'ClientStore' in the 'Startup.cs'.
Startup.cs:
var builder = services.AddIdentityServer(options =>
{
   options.EmitStaticAudienceClaim = true;
})
.AddClientStore<Core.ClientStore>();

Implement IResourceStore:

To load 'ApiResources' and 'ApiScopes' from the database by implementing the 'IResourceStore'. Let's add a new file in the 'Core' folder like 'ResourceStore.cs'
Core/ResourceStore.cs:
using AuthDemo.IdentityServer4.App.Data;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AuthDemo.IdentityServer4.App.Core
{
    public class ResourceStore : IResourceStore
    {
        private readonly AuthDbContext _authDbContext;
        public ResourceStore(AuthDbContext authDbContext)
        {
            _authDbContext = authDbContext;
        }
        public async Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(IEnumerable<string> apiResourceNames)
        {
            var dbApiResource = await _authDbContext.ApiResources.Select(_ => new ApiResource { Name = _.Name, DisplayName = _.DisplayName }).ToListAsync();

            var result = new List<ApiResource>();

            foreach (var name in apiResourceNames)
            {
                if(dbApiResource.Any(_ => _.Name.ToLower() == name.ToLower()))
                {
                    result.Add(dbApiResource.Where(_ => _.Name.ToLower() == name.ToLower()).First());
                }
            }
            return result;
        }

        public async Task<IEnumerable<ApiResource>> FindApiResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
        {
            var apiResourWithScopes = await _authDbContext.ApiResources
                .Join(
                _authDbContext.ApiResourceScopes,
                ar => ar.Id,
                ars => ars.ApiResourceId,
                (ar, ars) => new { ApiName = ar.Name, Scope = ars.Scope }
                ).ToListAsync();

            var groupedAPIResoruceScope = apiResourWithScopes.GroupBy(
                _ => _.ApiName)
                .Select(_ => new ApiResource { Name = _.Key, Scopes = _.Select(_ => _.Scope).ToList() })
                .ToList();

            var result = new List<ApiResource>();

            foreach (var name in scopeNames)
            {
                var matchedResource = groupedAPIResoruceScope.Where(_ => _.Scopes.Any(s => s.ToLower() == name.ToLower())).FirstOrDefault();
                if (matchedResource != null)
                {
                    result.Add(matchedResource);
                }
            }

            return result;
        }

        public async Task<IEnumerable<ApiScope>> FindApiScopesByNameAsync(IEnumerable<string> scopeNames)
        {
            var dbScopes = await _authDbContext.ApiResourceScopes.Select(_ => new ApiScope { Name = _.Scope }).ToListAsync();
            var result = new List<ApiScope>();
            foreach (var name in scopeNames)
            {
                var matchedApiScope = dbScopes.Where(_ => _.Name.ToLower() == name.ToLower()).FirstOrDefault();
                if (matchedApiScope != null)
                {
                    result.Add(matchedApiScope);
                }
            }
            return result;
        }

        public async Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
        {
            return new List<IdentityResource>() { };
        }

        public async Task<Resources> GetAllResourcesAsync()
        {
            var apiScopes = await _authDbContext.ApiResourceScopes.Select(_ => new ApiScope { Name = _.Scope }).ToListAsync();
            var apiResources = await _authDbContext.ApiResources.Select(_ => new ApiResource { Name = _.Name, DisplayName = _.DisplayName }).ToListAsync();

            return new Resources
            {
                ApiResources = apiResources,
                ApiScopes = apiScopes
            };
        }
    }
}
  • The IResourceStore provides 5 different methods that we have to implement.
  • (Line: 19-33) Implemented method 'FindApiResourcesByNameAsync'. So this method needs to be used for loading all the 'ApiResources' from the database by applying the 'ApiResourceName' filter. 
  • (Line: 35-62) Implemented method 'FindApiResourceByScopeNameAsync'. This method also returns collection ob 'ApiResource' but filtered by the 'scope names. So in this method, we write a join query between 'ApiResources' and 'ApiResourceScopes' and filter the output result by 'scope names'.
  • (Line: 64-77) Implemented method 'FindApiScopesByNameAsync'. Returns the 'ApiScopes' output data by using the 'scope names'.
  • (Line: 79-82) Implemented method 'FindIdentityResourceByScopeNameAsync'. For our client-credential demo we will just return empty result object.
  • (Line: 84-94) Implemented method 'GetAllResourceAsync'. This method gets invoked by '/.well-known/openid-configuration' IdentityServer endpoint to show all available scopes.
  • In these methods on receiving our client-credential request IdentiyServer automatically executes methods like 'FindApiResourceByScopeNameAsync', 'FindApiScopesbyNameAsync', 'FindIdentityResourceByScopeNameAsync'.
Now let's register our 'ResourceStore'
Startup.cs:
var builder = services.AddIdentityServer(options =>
{
	options.EmitStaticAudienceClaim = true;
})
.AddClientStore<Core.ClientStore>()
.AddResourceStore<Core.ResourceStore>();
So that's all our IdentityServer ready to deliver the Jwt access token for valid client credentials requests.

Create A .Net5 Web API Protected By Our IdentityServer:

Create a .Net WEB API protected by our IdentityServer which means our newly created API is one of the IdentityServer 'ApiResources'. So clients can use the JWT token provided by the IdentiyServer against our new API for authentication.

Since our IdentiyServer uses a port number like '5000' and '5001', so in our protected API let's change them to '6000' and '60001' in the 'Properties/launchSetting.json' file.

Now to validate the JWT token first let's install the NuGet package.

Now in the 'Startup.cs' we have to configure authentication middleware and then need to register the Bearer authentication service.
Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Protected.DemoAPI
{
    public class Startup
    {
       
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5001"; // identiy server domain
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidAudience = "API1",
                        ValidateAudience = true
                    };
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
        }
    }
}
// existing code hidden for display purpose
  • (Line: 22-31) Enabled 'Bearer' token authentication service.
  • (Line: 25) The 'Authority' value can be the domain of our IdentiyServer.
  • (Line: 28) The 'ValidAudience' value is the name of our  'ApiResource' name in the IdentiyServer. IdentiyServer generates 'aud' claim with the name of 'ApiResource'.
  • (Line: 29) Enabled audience validation.
  • (Line: 37) Add the 'UseAuthentication' middleware just above the 'UseAuthorization' middleware.
The 'Scope' value jwt token can be used for authorization so let's register the policies for the authorization.
Startup.cs:
services.AddAuthorization(options =>
{
	options.AddPolicy("PolicyScope1", policy =>
	{
		policy.RequireAuthenticatedUser();
		policy.RequireClaim("scope", "API1.read");
	});
	options.AddPolicy("PolicyScope2", policy =>
	{
		policy.RequireAuthenticatedUser();
		policy.RequireClaim("scope", "API1.readmore");
	});
});
  • Here I added 2 policies, for my client only has the first scope doesn't have the second scope, so here we can test both successes and fail cases of authorization.
Now let's add a 'TestController.cs', in that lets add 3 action methods. The first action method is decorated with the normal 'Authorize' attribute. The second action method is decorated with policy-based authorization like 'PolicyScope1'. The third action method is decorated with policy-based authorization like 'PolicyScope 2'.
Controllers/TestController.cs:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Protected.DemoAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("case1")]
        [Authorize]
        public IActionResult Case1()
        {
            return Ok("Hi simple authorization enabled");
        }

        [HttpGet]
        [Route("case2")]
        [Authorize(Policy = "PolicyScope1")]
        public IActionResult Case2()
        {
            return Ok("Hi policy base authorization enabled");
        }

        [HttpGet]
        [Route("case3")]
        [Authorize(Policy = "PolicyScope2")]
        public IActionResult Case3()
        {
            return Ok("Hi policy base authorization enabled");
        }

    }
}

Test From Postman Tool:

So first let's run our IdentityServer(runs on port 5000,5001) and Protected Resource API(runs on port 6000, 6001).

Now let's try to consume the below-secured endpoint.
https://localhost:6001/api/test/case1

Now click on the 'Get New Access Token' button a popover appears where we have to pass values like
'Access Token URL'(https://localhost:5001/connect/token), 'Client ID', 'Client Secret','Scope'(optional),'Grant Type'.
Once we received tokens from our IdentityServer, then select  'Add token to'(value like Header) and then click 'Use Token' then the token is automatically added as a header value to our API request.

Now send the request and check the output

Now test the 2nd endpoint.
https://localhost:6001/api/test/case2

Now test 3rd endpoint which is decorated with the different policy so it returns 403 status because our client doesn't have access to the scope used in this policy.

Create A Client API To Consume Protected API With HttpClient:

Now let's try to consume the protected API from other applications like API, Console Application, Mobile Application, etc. So let's create a new web API application(eg:- Client.DemoAPI name of the project) for our testing. Change the port number of our Client API to '7001' and '7000' in 'Properties/launchsettings.json'.

In 'Startup.cs' let's register our 'IdentiyServer' and 'Protected API' domains with the HttpClient factory with their own respective names.
Startup.cs:
services.AddHttpClient("IdentityServer", options =>
{
	options.BaseAddress = new Uri("https://localhost:5001/");
});

services.AddHttpClient("ProtectedAPI", options =>
{
	options.BaseAddress = new Uri("https://localhost:6001/");
});
Now let's create a token response model. So first create a folder like 'Models' and then add file 'AccessTokenResponse.cs'
Models/AccessTokenResponse:
using System.Text.Json.Serialization;

namespace Client.DemoAPI.Models
{
    public class AccessTokenResponse
    {
        [JsonPropertyName("access_token")]
        public string AccessToken { get; set; }

        [JsonPropertyName("expires_in")]
        public int ExpiresIn { get; set; }

        [JsonPropertyName("token_type")]
        public string TokenType { get; set; }

        [JsonPropertyName("scope")]
        public string scope { get; set; }
    }
}
Now let's create 'DemoController.cs' where we will implement logic to invoking the IdentiyServer for token and then consuming the Protected API.
Controllers/DemoController.cs:
using Client.DemoAPI.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace Client.DemoAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public DemoController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        
        private async Task<AccessTokenResponse> GetAccessToken()
        {
            var credentials = new Dictionary<string, string>
            {
                {"client_id","MyClient" },
                {"client_secret", "MySecrets" },
                {"grant_type","client_credentials" }
            };
            HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Post, "connect/token");
            reqMsg.Content = new FormUrlEncodedContent(credentials);

            var httpClient = _httpClientFactory.CreateClient("IdentityServer");
            var response = await httpClient.SendAsync(reqMsg);
            response.EnsureSuccessStatusCode();
            var data = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<AccessTokenResponse>(data);
        }

        [Route("consumer-protected-api")]
        [HttpGet]
        public async Task<IActionResult> ConsumeProtectedApi()
        {
            var tokenResponse = await GetAccessToken();

            HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, "api/test/case2");
            reqMsg.Headers.Add("Authorization", $"{tokenResponse.TokenType} {tokenResponse.AccessToken}");

            var httpClient = _httpClientFactory.CreateClient("ProtectedAPI");
            var response = await httpClient.SendAsync(reqMsg);
            response.EnsureSuccessStatusCode();
            return Ok(await response.Content.ReadAsStringAsync());
        }
    }
}
  • (Line: 15) Injected 'IHttpClientFactory'.
  • (Line: 21-37) The method 'GetAccessToken()' invokes the identity server token endpoint.
  • (Line: 23-28) Preparing the form payload that is client credentials for authentication.
  • (Line: 32-36) Invoking the token endpoint and fetching the access token response.
  • (Line: 39-53) Our action method is to consume the Protected API.
  • (Line: 46) Adding our access token as 'Authorization' header.
  • (Line: 48-51) Invoking the Protected API and then returning the response.
Now run all 3 applications like 'IdentiyServer', 'Protected API', 'Client API'.

Video Session:

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on IdentityServer4 With Client Credentials Authentication. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl