How IdentityServer3 Handles Client Credentials Flow

Identity Server 3 supports the Client Credentials OAuth2 grant.  I wrote a brief introduction to both OAuth2 and IdentityServer3 last month, this is a follow-on article exploring some other facets of authentication.

This is a little bit like basic authentication, in that the client (the application which wants to consume a WebAPI) passes a preshared key to ID3 in exchange for a bearer token.

The values passed from the Client to ID3 can be specified in either the HTTP/S header or body of the POST request.  I prefer specifying it in the Header.

The format is as follows:

Authorization: Basic (“Client ID” + “Client Secret”)

Where:

  • “Client ID” is the ID for the application (“Client”) in ID3
  • “Client Secret” is the unencrypted version of the client secret stored in ID3’s database
  • The Parenthesis indicates that the content should be Base64 encoded

The POST request also needs to contain the authorization flow type (client_credentials in this case) and intended scope (target) in the Body of the request.

The following PowerShell script demonstrates how to assemble a valid bearer token request:

function Hash($textToHash)
{
      $toHash = [System.Text.Encoding]::UTF8.GetBytes($textToHash)
      return [System.Convert]::ToBase64String($toHash)
}

$authUri = "https://identityserver/"
$authPostUri = "https://identityserver/connect/token"
$scope =  "someTargetApiName"
$client_id = "clientApplicationName"
$client_secret = "6FB76F91-B62D-4193-A795-FDDF405F94A2"
$grant_type = "client_credentials"
$value = Hash($client_id + ":" + $client_secret)
$auth = "Basic " + $value
$body = "grant_type=" + $grant_type
$body += "&scope=" + $scope
$resp = try { 
Invoke-RestMethod -Method Post -Uri $authPostUri -Headers @{ "Authorization" = $auth } -Body $body
} catch { $_.Exception.Response }

Which produces a HTTP POST request which looks like this:


 

POST https://identityserver/connect/token HTTP/1.1
Authorization: Basic c3lzdGVtQ29kZXN000JpcHQ6NkZCNzZGOTEtQjYyRC00MTkzLUE3OTUtRk000jQwNUY5NEEy
Content-Type: application/x-www-form-urlencoded
Host: identityserver
Content-Length: 55
Expect: 100-continue
Connection: Keep-Alive

grant_type=client_credentials&scope=someTargetApiName

Which, if successful, would return the following response from ID3:

@{access_token=dea839e9d3e09b4d4c00ba1fb479646a; expires_in=3600; token_type=Bearer}

Next up, I’ll show you how to generate the client secret and how to handle it on the client and within ID3’s database.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “How IdentityServer3 Handles Client Credentials Flow”