Retrieving, using and validating token from an IdentityServer


📮 Contact 🇧🇷 🇺🇸 🇫🇷


This is an example of how to a client application retrieves a token from a Identity Server and use it in an WebApi to consumes an endpoint.

How this project was created

This example was built based on Duende documentation

Identity Server

Identity provider for our sample.

Install Duende templates

dotnet new --install Duende.IdentityServer.Templates

Create an empty solution

dotnet new sln -n IdentityServerDemo

Create Identity server project

dotnet new isempty -n IdentityServer

Add IdendityServer projet to the blank solution

dotnet sln add .IdentityServerIdentityServer.csproj

Add scope to config.cs

public static IEnumerable<ApiScope> ApiScopes =>
    new ApiScope[]
        { new ApiScope(name: "campelo-api", displayName: "CampeloAPI") };

Add client to config.cs

public static IEnumerable<Client> Clients =>
    new Client[]
        { new Client
            ClientId = "client",
            // no interactive user, use the clientid/secret for authentication
            AllowedGrantTypes = GrantTypes.ClientCredentials,
            // secret for authentication
            ClientSecrets =
                new Secret("secret".Sha256())
            // scopes that client has access to
            AllowedScopes = { "campelo-api" }
        } };


Now you can access openid-configuration from the identity server. Run the solution and go to https://localhost:5001/.well-known/openid-configuration. So you can retrieve something like this.

      "id_token token",
      "code id_token",
      "code token",
      "code id_token token"

API project

Web API project.

Create a new web API project

dotnet new webapi -n WebApi

Adding webapi to the solution

dotnet sln add .WebApiWebApi.csproj

Adding JWT Bearer authentication

dotnet add .WebApiWebApi.csproj package Microsoft.AspNetCore.Authentication.JwtBearer

Set JWT Bearer as the default authentication scheme

Update the Program.cs or Startup.cs file.

    .AddJwtBearer("Bearer", options =>
        options.Authority = "https://localhost:5001";

        options.TokenValidationParameters = new TokenValidationParameters
            ValidateAudience = false

/// UseAuthentication right before UseAuthorization

Add a new controller for testing

public class IdentityController : ControllerBase
    public IActionResult Get()
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });

Configure the WebAPI to listen on Port 6001

Edit the launchSettings.json file in Properties folder.

"applicationUrl": "https://localhost:6001"

Run the WebAPI project

Now you have a 401 (unauthorized) error response when trying to access https://localhost:6001/identity

Client project

Create a console client project

dotnet new console -n Client

Add the client project to the solution

dotnet sln add .ClientClient.csproj

Add IdentityModel to the client project

dotnet add .ClientClient.csproj package IdentityModel

Discover endpoints from metadata

var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
if (disco.IsError)

Request token

var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    Address = disco.TokenEndpoint,

    ClientId = "client",
    ClientSecret = "secret",
    Scope = "campelo-api"

if (tokenResponse.IsError)


Call WebAPI

var apiClient = new HttpClient();

var response = await apiClient.GetAsync("https://localhost:6001/identity");
if (!response.IsSuccessStatusCode)
    var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
    Console.WriteLine(JsonSerializer.Serialize(doc, new JsonSerializerOptions { WriteIndented = true }));

Run client

Be sure that the IdentityServer and WebAPI are running and run the Client project to see something like this
Image 1

Source code

Source code

Typos or suggestions?

If you’ve found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly to and open a new pull request with your changes.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

The B2B SaaS Sales Funnel: How Your Brand Can Optimize It to Boost Conversions

Next Post

Top 7 Featured DEV Posts from the Past Week

Related Posts