Sample code for 30+ languages & platforms
Unicode C

OAuth2 Token using IdentityServer4 with Client Credentials

See more OAuth2 Examples

Demonstrates how to get an OAuth2 access token using the client credential flow with IdentityServer4.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkHttpW.h>
#include <C_CkHttpResponseW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkJsonArrayW.h>
#include <C_CkHttpRequestW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkHttpW http;
    HCkHttpResponseW resp;
    HCkJsonObjectW json;
    const wchar_t *tokenEndpoint;
    HCkJsonArrayW grantTypes;
    int clientCredentialsIdx;
    HCkHttpRequestW req;
    const wchar_t *accessToken;

    success = FALSE;

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    http = CkHttpW_Create();

    // The first step is to fetch your IdentityServer4's discovery document
    // (OpenID Connect defines a discovery mechanism, called OpenID Connect Discovery, where an OpenID server publishes its metadata at a well-known URL, 
    // typically https://server.com/.well-known/openid-configuration

    resp = CkHttpResponseW_Create();
    success = CkHttpW_HttpNoBody(http,L"GET",L"https://localhost:5000/.well-known/openid-configuration",resp);
    if (success == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkHttpResponseW_Dispose(resp);
        return;
    }

    if (CkHttpResponseW_getStatusCode(resp) != 200) {
        wprintf(L"Received response status code %d\n",CkHttpResponseW_getStatusCode(resp));
        wprintf(L"Response body containing error text or JSON:\n");
        wprintf(L"%s\n",CkHttpResponseW_bodyStr(resp));
        CkHttpW_Dispose(http);
        CkHttpResponseW_Dispose(resp);
        return;
    }

    json = CkJsonObjectW_Create();
    success = CkJsonObjectW_Load(json,CkHttpResponseW_bodyStr(resp));

    // We have the discovery document, which contains something like this:

    // You can use this online tool to generate parsing code from sample JSON: 
    // Generate Parsing Code from JSON

    // {
    //   "issuer": "https://localhost:5000",
    //   "jwks_uri": "https://localhost:5000/.well-known/openid-configuration/jwks",
    //   "authorization_endpoint": "https://localhost:5000/connect/authorize",
    //   "token_endpoint": "https://localhost:5000/connect/token",
    //   "userinfo_endpoint": "https://localhost:5000/connect/userinfo",
    //   "end_session_endpoint": "https://localhost:5000/connect/endsession",
    //   "check_session_iframe": "https://localhost:5000/connect/checksession",
    //   "revocation_endpoint": "https://localhost:5000/connect/revocation",
    //   "introspection_endpoint": "https://localhost:5000/connect/introspect",
    //   "frontchannel_logout_supported": true,
    //   "frontchannel_logout_session_supported": true,
    //   "backchannel_logout_supported": true,
    //   "backchannel_logout_session_supported": true,
    //   "scopes_supported": [
    //     "openid",
    //     "profile",
    //     "email",
    //     "MyCompany.profile",
    //     "MyCompany.Identity.WebApi",
    //     "MyCompany.TriHub.WebApi",
    //     "offline_access"
    //   ],
    //   "claims_supported": [
    //     "sub",
    //     "updated_at",
    //     "locale",
    //     "zoneinfo",
    //     "birthdate",
    //     "gender",
    //     "website",
    //     "profile",
    //     "preferred_username",
    //     "nickname",
    //     "middle_name",
    //     "given_name",
    //     "family_name",
    //     "name",
    //     "picture",
    //     "email_verified",
    //     "email",
    //     "userId",
    //     "groups",
    //     "fullname"
    //   ],
    //   "grant_types_supported": [
    //     "authorization_code",
    //     "client_credentials",
    //     "refresh_token",
    //     "implicit",
    //     "password"
    //   ],
    //   "response_types_supported": [
    //     "code",
    //     "token",
    //     "id_token",
    //     "id_token token",
    //     "code id_token",
    //     "code token",
    //     "code id_token token"
    //   ],
    //   "response_modes_supported": [
    //     "form_post",
    //     "query",
    //     "fragment"
    //   ],
    //   "token_endpoint_auth_methods_supported": [
    //     "client_secret_basic",
    //     "client_secret_post"
    //   ],
    //   "subject_types_supported": [
    //     "public"
    //   ],
    //   "id_token_signing_alg_values_supported": [
    //     "RS256"
    //   ],
    //   "code_challenge_methods_supported": [
    //     "plain",
    //     "S256"
    //   ]
    // }
    // 

    // The next steps are to (1) get the token_endpoint,
    // and (2) verify that the client_credentials grant type is supported.

    tokenEndpoint = CkJsonObjectW_stringOf(json,L"token_endpoint");

    grantTypes = CkJsonObjectW_ArrayOf(json,L"grant_types_supported");
    clientCredentialsIdx = CkJsonArrayW_FindString(grantTypes,L"client_credentials",TRUE);
    CkJsonArrayW_Dispose(grantTypes);

    // If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
    if (clientCredentialsIdx < 0) {
        wprintf(L"The client credentials grant type is not supported.\n");
        CkHttpW_Dispose(http);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(json);
        return;
    }

    // Request the access token using our Client ID and Client Secret.
    // We're going to duplicate this CURL statement:

    // curl --request POST \
    //   --url '<tokenEndpoint>' \
    //   --header 'content-type: application/x-www-form-urlencoded' \
    //   --data 'grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET'

    req = CkHttpRequestW_Create();
    CkHttpRequestW_putHttpVerb(req,L"POST");
    CkHttpRequestW_putContentType(req,L"application/x-www-form-urlencoded");

    CkHttpRequestW_AddParam(req,L"grant_type",L"client_credentials");
    CkHttpRequestW_AddParam(req,L"client_id",L"CLIENT_ID");
    CkHttpRequestW_AddParam(req,L"client_secret",L"CLIENT_SECRET");    CkHttpRequestW_putHttpVerb(req,L"POST");

    success = CkHttpW_HttpReq(http,tokenEndpoint,req,resp);
    if (success == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(json);
        CkHttpRequestW_Dispose(req);
        return;
    }

    // Make sure we got a 200 response status code, otherwise it's an error.
    if (CkHttpResponseW_getStatusCode(resp) != 200) {
        wprintf(L"POST to token endpoint failed.\n");
        wprintf(L"Received response status code %d\n",CkHttpResponseW_getStatusCode(resp));
        wprintf(L"Response body containing error text or JSON:\n");
        wprintf(L"%s\n",CkHttpResponseW_bodyStr(resp));
        CkHttpW_Dispose(http);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(json);
        CkHttpRequestW_Dispose(req);
        return;
    }

    success = CkJsonObjectW_Load(json,CkHttpResponseW_bodyStr(resp));

    // Our JSON response should contain this:
    // {
    //   "access_token":"eyJz93a...k4laUWw",
    //   "token_type":"Bearer",
    //   "expires_in":86400
    // }

    // Get the access token:
    accessToken = CkJsonObjectW_stringOf(json,L"access_token");

    // The access token is what gets added to "Authorization: Bearer <access_token>"
    // for the subsequent REST API calls..


    CkHttpW_Dispose(http);
    CkHttpResponseW_Dispose(resp);
    CkJsonObjectW_Dispose(json);
    CkHttpRequestW_Dispose(req);

    }