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.
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.
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.
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.
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.
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.
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.
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.
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'.
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'.
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.
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.
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
'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
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.
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.
Comments
Post a Comment