Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

C Examples

Web API Categories

ASN.1
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks

Gzip
HTML-to-XML/Text
HTTP
HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
NTLM
OAuth1
OAuth2
Office365
OneDrive
OpenSSL
Outlook
PEM
PFX/P12
POP3
PRNG
REST
REST Misc
RSA
SCP
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
SharePoint
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(C) Uni Economy API Client Credentials Flow

Demonstrates how to do OAuth 2.0 using the client credentials flow for the Uni Economy API. (This means that the server can authenticate against the identity server without human interaction.)

For more information, see https://developer.unieconomy.no/wiki/introduction/getting-started/server-application

Chilkat C/C++ Library Downloads

MS Visual C/C++

Linux/CentOS C/C++

Alpine Linux C/C++

MAC OS X C/C++

armhf/aarch64 C/C++

C++ Builder

iOS C/C++

Android C/C++

Win Mobile 5.0/Pocket PC 2003

Solaris C/C++

FreeBSD C/C++

OpenBSD C/C++

MinGW C/C++

#include <C_CkCert.h>
#include <C_CkPrivateKey.h>
#include <C_CkJwt.h>
#include <C_CkJsonObject.h>
#include <C_CkCrypt2.h>
#include <C_CkHttp.h>
#include <C_CkHttpResponse.h>
#include <C_CkJsonArray.h>
#include <C_CkHttpRequest.h>
#include <C_CkStringBuilder.h>

void ChilkatSample(void)
    {
    HCkCert cert;
    BOOL success;
    HCkPrivateKey privKey;
    HCkJwt jwt;
    HCkJsonObject jose;
    const char *myClientId;
    HCkJsonObject claims;
    HCkCrypt2 crypt;
    int curDateTime;
    const char *jwt_token;
    HCkHttp http;
    HCkHttpResponse resp;
    HCkJsonObject json;
    const char *tokenEndpoint;
    HCkJsonArray grantTypes;
    int clientCredentialsIdx;
    HCkHttpRequest req;
    const char *accessToken;
    HCkStringBuilder sbResponse;

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

    // Step 1 ------------------------------------------------------------------------------------------
    // First create a client token...

    cert = CkCert_Create();
    CkCert_putVerboseLogging(cert,TRUE);
    // Note: .pfx and .p12 files are identical.  The only difference is the file extension.
    // Also, if your .p12 password is longer than 64 chars, you'll need Chilkat v9.5.0.83 or later.
    // To shorten the password, import your .p12 onto your Windows computer by double-clicking on the .p12 file,
    // make sure when importing that keys are exportable, then re-export with private keys to a .pfx with a new password.
    success = CkCert_LoadPfxFile(cert,"qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret");
    if (success == FALSE) {
        printf("%s\n",CkCert_lastErrorText(cert));
        CkCert_Dispose(cert);
        return;
    }

    privKey = CkCert_ExportPrivateKey(cert);
    if (CkCert_getLastMethodSuccess(cert) == FALSE) {
        printf("%s\n",CkCert_lastErrorText(cert));
        CkCert_Dispose(cert);
        return;
    }

    jwt = CkJwt_Create();

    // Build the JOSE header
    jose = CkJsonObject_Create();
    // Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
    success = CkJsonObject_AppendString(jose,"alg","RS256");
    success = CkJsonObject_AppendString(jose,"typ","JWT");

    // Now build the JWT claims (also known as the payload)

    // Our JWT claims will contain members as shown here:
    // {
    //   "jti": "ad612fce-3e71-4f6a-8af1-7eb0414b4eea",  <-- generated unique global identifier
    //   "sub": "99999999-aaaa-bbbb-cccc-ddddeeeeffff",  <-- This is the clientId
    //   "iat": 1588102982,  <-- These are date/time values.
    //   "nbf": 1588102982,
    //   "exp": 1588103042,
    //   "iss": " 99999999-aaaa-bbbb-cccc-ddddeeeeffff",
    //   "aud": "https://test-login.unieconomy.no/connect/token"
    // }

    // Use your own client ID.
    myClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff";

    claims = CkJsonObject_Create();
    crypt = CkCrypt2_Create();
    CkJsonObject_AppendString(claims,"jti",CkCrypt2_generateUuid(crypt));
    CkJsonObject_AppendString(claims,"sub",myClientId);

    // Set the timestamp of when the JWT was created to now minus 60 seconds
    curDateTime = CkJwt_GenNumericDate(jwt,-60);
    success = CkJsonObject_AddIntAt(claims,-1,"iat",curDateTime);

    // Set the "not process before" timestamp to now minus 60 seconds
    success = CkJsonObject_AddIntAt(claims,-1,"nbf",curDateTime);

    // Set the timestamp defining an expiration time (end time) for the token
    // to be now + 1 hour (3600 seconds)
    success = CkJsonObject_AddIntAt(claims,-1,"exp",curDateTime + 3600);

    CkJsonObject_AppendString(claims,"iss",myClientId);
    CkJsonObject_AppendString(claims,"aud","https://test-login.unieconomy.no/connect/token");

    // Produce the smallest possible JWT:
    CkJwt_putAutoCompact(jwt,TRUE);

    // Create the JWT token.  This is where the RSA signature is created.
    jwt_token = CkJwt_createJwtPk(jwt,CkJsonObject_emit(jose),CkJsonObject_emit(claims),privKey);

    printf("%s\n",jwt_token);

    // Step 2 ------------------------------------------------------------------------------------------
    http = CkHttp_Create();

    // Fetch the discovery document...
    resp = CkHttp_QuickRequest(http,"GET","https://test-login.unieconomy.no/.well-known/openid-configuration");
    if (CkHttp_getLastMethodSuccess(http) != TRUE) {
        printf("%s\n",CkHttp_lastErrorText(http));
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        return;
    }

    if (CkHttpResponse_getStatusCode(resp) != 200) {
        printf("Received response status code %d\n",CkHttpResponse_getStatusCode(resp));
        printf("Response body containing error text or JSON:\n");
        printf("%s\n",CkHttpResponse_bodyStr(resp));
        CkHttpResponse_Dispose(resp);
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        return;
    }

    json = CkJsonObject_Create();
    success = CkJsonObject_Load(json,CkHttpResponse_bodyStr(resp));
    CkHttpResponse_Dispose(resp);

    CkJsonObject_putEmitCompact(json,FALSE);
    printf("%s\n",CkJsonObject_emit(json));

    // 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://test-login.unieconomy.no",
    //   "jwks_uri": "https://test-login.unieconomy.no/.well-known/openid-configuration/jwks",
    //   "authorization_endpoint": "https://test-login.unieconomy.no/connect/authorize",
    //   "token_endpoint": "https://test-login.unieconomy.no/connect/token",
    //   "userinfo_endpoint": "https://test-login.unieconomy.no/connect/userinfo",
    //   "end_session_endpoint": "https://test-login.unieconomy.no/connect/endsession",
    //   "check_session_iframe": "https://test-login.unieconomy.no/connect/checksession",
    //   "revocation_endpoint": "https://test-login.unieconomy.no/connect/revocation",
    //   "introspection_endpoint": "https://test-login.unieconomy.no/connect/introspect",
    //   "device_authorization_endpoint": "https://test-login.unieconomy.no/connect/deviceauthorization",
    //   "frontchannel_logout_supported": true,
    //   "frontchannel_logout_session_supported": true,
    //   "backchannel_logout_supported": true,
    //   "backchannel_logout_session_supported": true,
    //   "scopes_supported": [
    //     "openid",
    //     "profile",
    //     "email",
    //     "offline_access",
    //     "AppFramework.All",
    //     "AppFramework",
    //     "AppFramework.Sales",
    //     "IdentityAPI",
    //     "widgetApi",
    //     "TestScope.test",
    //     "TestScope.Cars",
    //     "HaglandAPI",
    //     "LicenseAdmin",
    //     "LicenseAdmin.Product.Read",
    //     "SoftRig.Product.Write",
    //     "TestAPI.test",
    //     "offline_access"
    //   ],
    //   "claims_supported": [
    //     "sub",
    //     "updated_at",
    //     "name",
    //     "family_name",
    //     "given_name",
    //     "middle_name",
    //     "nickname",
    //     "preferred_username",
    //     "picture",
    //     "website",
    //     "gender",
    //     "birthdate",
    //     "zoneinfo",
    //     "locale",
    //     "profile",
    //     "email",
    //     "email_verified"
    //   ],
    //   "grant_types_supported": [
    //     "authorization_code",
    //     "client_credentials",
    //     "refresh_token",
    //     "implicit",
    //     "password",
    //     "urn:ietf:params:oauth:grant-type:device_code",
    //     "delegation"
    //   ],
    //   "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",
    //     "private_key_jwt",
    //     "private_key_jwt"
    //   ],
    //   "id_token_signing_alg_values_supported": [
    //     "RS256"
    //   ],
    //   "subject_types_supported": [
    //     "public"
    //   ],
    //   "code_challenge_methods_supported": [
    //     "plain",
    //     "S256"
    //   ],
    //   "request_parameter_supported": true
    // }

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

    tokenEndpoint = CkJsonObject_stringOf(json,"token_endpoint");

    grantTypes = CkJsonObject_ArrayOf(json,"grant_types_supported");
    clientCredentialsIdx = CkJsonArray_FindString(grantTypes,"client_credentials",TRUE);
    CkJsonArray_Dispose(grantTypes);

    // If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
    if (clientCredentialsIdx < 0) {
        printf("The client credentials grant type is not supported.\n");
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(json);
        return;
    }

    // ------------------------------------------------------
    // Request the access token using our Client ID and JWT

    req = CkHttpRequest_Create();
    CkHttpRequest_putHttpVerb(req,"POST");
    CkHttpRequest_AddParam(req,"client_id",myClientId);
    CkHttpRequest_AddParam(req,"scope","AppFramework.Sales");
    CkHttpRequest_AddParam(req,"grant_type","client_credentials");
    CkHttpRequest_AddParam(req,"client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    CkHttpRequest_AddParam(req,"client_assertion",jwt_token);

    resp = CkHttp_PostUrlEncoded(http,tokenEndpoint,req);
    if (CkHttp_getLastMethodSuccess(http) == FALSE) {
        printf("%s\n",CkHttp_lastErrorText(http));
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(json);
        CkHttpRequest_Dispose(req);
        return;
    }

    // Make sure we got a 200 response status code, otherwise it's an error.
    if (CkHttpResponse_getStatusCode(resp) != 200) {
        printf("POST to token endpoint failed.\n");
        printf("Received response status code %d\n",CkHttpResponse_getStatusCode(resp));
        printf("Response body containing error text or JSON:\n");
        printf("%s\n",CkHttpResponse_bodyStr(resp));
        CkHttpResponse_Dispose(resp);
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(json);
        CkHttpRequest_Dispose(req);
        return;
    }

    success = CkJsonObject_Load(json,CkHttpResponse_bodyStr(resp));
    CkHttpResponse_Dispose(resp);

    printf("%s\n",CkJsonObject_emit(json));

    // The JSON response will look like this:

    // {
    //   "access_token": "...",
    //   "expires_in": 3600,
    //   "token_type": "Bearer",
    //   "scope": "AppFramework.Sales"
    // }

    // Get the access token:
    accessToken = CkJsonObject_stringOf(json,"access_token");
    printf("accessToken = %s\n",accessToken);

    // ------------------------------------------------------
    // Use the access token in a request.
    // We'll just send a GET request to  https://test.unieconomy.no/api/init/companies

    // Tell the http object to use the OAuth2 access token in the "Authorization: Bearer ..." header.
    CkHttp_putAuthToken(http,accessToken);

    sbResponse = CkStringBuilder_Create();
    success = CkHttp_QuickGetSb(http,"https://test.unieconomy.no/api/init/companies",sbResponse);
    if (success == FALSE) {
        printf("%s\n",CkHttp_lastErrorText(http));
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(json);
        CkHttpRequest_Dispose(req);
        CkStringBuilder_Dispose(sbResponse);
        return;
    }

    // Examine the response status code.
    if (CkHttp_getLastStatus(http) != 200) {
        printf("%s\n",CkStringBuilder_getAsString(sbResponse));
        printf("response status: %d\n",CkHttp_getLastStatus(http));
        printf("Received error response.\n");
        CkCert_Dispose(cert);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(jose);
        CkJsonObject_Dispose(claims);
        CkCrypt2_Dispose(crypt);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(json);
        CkHttpRequest_Dispose(req);
        CkStringBuilder_Dispose(sbResponse);
        return;
    }

    CkJsonObject_LoadSb(json,sbResponse);
    printf("%s\n",CkJsonObject_emit(json));

    printf("Success.\n");


    CkCert_Dispose(cert);
    CkJwt_Dispose(jwt);
    CkJsonObject_Dispose(jose);
    CkJsonObject_Dispose(claims);
    CkCrypt2_Dispose(crypt);
    CkHttp_Dispose(http);
    CkJsonObject_Dispose(json);
    CkHttpRequest_Dispose(req);
    CkStringBuilder_Dispose(sbResponse);

    }

 

© 2000-2020 Chilkat Software, Inc. All Rights Reserved.