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

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

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

.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

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

NestJS File Upload

In this article, we are going to understand the steps to create a file uploading endpoint in the NestJS application. Key Features In NestJS File Upload: Let us know some key features of NestJS file upload before implementing a sample application. FileInterceptor: The 'FileInterceptor' will be decorated on top of the file upload endpoint. This interceptor will read single file data from the form posted to the endpoint. export declare function FilesInterceptor(fieldName: string, localOptions?: MulterOptions): Type<NestInterceptor>; Here we can observe the 'fieldName' first input parameter this value should be a match with our 'name' attribute value on the form file input field. So our interceptor read our files that are attached to the file input field. Another input parameter of 'MulterOptions' that provides configuration like file destination path, customizing file name, etc. FilesInterceptor: The 'FilesInterceptor' will be decorated on t

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http