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

  1. hi i dont have identity server4 template so can i use identity server4 pakage

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update 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 the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the 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 the authentication with HTTP-only JWT cookie then we no need to implement the 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 authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.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

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

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

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

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

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