Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

C Examples

Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Cloud Signature CSC
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
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
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
Secrets
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl
uncategorized

 

 

 

(C) Azure OpenID Connect Step 2 -- Get id_token and Validate

See more OIDC Examples

After getting the endpoints by querying the Azure's OIDC well-known discovery document (OpenID Configuration document), we use the authorization_endpoint to get the id_token, and then validate it..

For more information, see https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc

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++

Solaris C/C++

MinGW C/C++

#include <C_CkHttpRequest.h>
#include <C_CkPrng.h>
#include <C_CkStringBuilder.h>
#include <C_CkSocket.h>
#include <C_CkTask.h>
#include <C_CkHashtable.h>
#include <C_CkJwt.h>
#include <C_CkJsonObject.h>
#include <C_CkHttp.h>
#include <C_CkPublicKey.h>

void ChilkatSample(void)
    {
    BOOL success;
    const char *authorization_endpoint;
    const char *jwks_uri;
    HCkHttpRequest req;
    HCkPrng prng;
    const char *encodedParams;
    HCkStringBuilder sbUrl;
    const char *url;
    HCkSocket listenSock;
    int backLog;
    int maxWaitMs;
    HCkTask task;
    HCkSocket sock;
    const char *startLine;
    const char *requestHeader;
    HCkStringBuilder sbRequestBody;
    HCkStringBuilder sbResponseHtml;
    HCkStringBuilder sbResponse;
    HCkHashtable hashTab;
    const char *idToken;
    HCkJwt jwt;
    int leeway;
    BOOL bTimeValid;
    const char *payload;
    HCkJsonObject json;
    const char *joseHeader;
    HCkJsonObject jsonJoseHeader;
    HCkStringBuilder sbJwks;
    HCkHttp http;
    HCkJsonObject jwkset;
    const char *kid;
    HCkJsonObject jwk;
    BOOL verified;
    HCkPublicKey pubkey;

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

    // In our previous example (Azure Fetch OpenID Connect metadata document) we fetched
    // the OpenID configuration document which is JSON which contains an entry for authorization_endpoint.

    authorization_endpoint = "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/oauth2/v2.0/authorize";

    // The OpenID Connect metadata document also contained a jwks_uri entry.  This is the JSON Web Key Set (JWKS),
    // which is a set of keys containing the public keys used to verify any JSON Web Token (JWT) (in this case the id_token)
    // issued by the authorization server and signed using the RS256 signing algorithm. 
    jwks_uri = "https://login.microsoftonline.com/6d8ddd66-68d1-44b0-af5c-e31b4b7ee5cd/discovery/v2.0/keys";

    // We're going to send the following GET request, but it will be sent through an interactive web browser (not by Chilkat).
    // The following code will form the URL that is to be programmatically loaded and sent in a browser.

    // GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
    // client_id=6731de76-14a6-49ae-97bc-6eba6914391e
    // &response_type=id_token
    // &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    // &response_mode=form_post
    // &scope=openid
    // &state=12345
    // &nonce=678910

    // Use this object to set params and then get the URL-encoded query params string 
    req = CkHttpRequest_Create();
    CkHttpRequest_AddParam(req,"client_id","f125d695-c50e-456e-a579-a486f06d1213");
    CkHttpRequest_AddParam(req,"response_type","id_token");
    CkHttpRequest_AddParam(req,"redirect_uri","http://localhost:3017/");
    CkHttpRequest_AddParam(req,"response_mode","form_post");
    CkHttpRequest_AddParam(req,"scope","openid");
    prng = CkPrng_Create();
    CkHttpRequest_AddParam(req,"state",CkPrng_genRandom(prng,3,"decimal"));
    CkHttpRequest_AddParam(req,"nonce",CkPrng_genRandom(prng,4,"decimal"));

    encodedParams = CkHttpRequest_getUrlEncodedParams(req);
    printf("%s\n",encodedParams);

    // Sample URL encoded params:
    // client_id=6731de76-14a6-49ae-97bc-6eba6914391e&redirect_uri=http%3A%2F%2Flocalhost%3A3017%2F&response_mode=form_post&scope=openid&state=3572902&nonce=57352474

    // This is the URL to be programmatically loaded and sent in an interactive web browser..
    sbUrl = CkStringBuilder_Create();
    CkStringBuilder_Append(sbUrl,authorization_endpoint);
    CkStringBuilder_Append(sbUrl,"?");
    CkStringBuilder_Append(sbUrl,encodedParams);
    url = CkStringBuilder_getAsString(sbUrl);

    // Before we launch the browser with the contents of sbUrl, create a socket to listen for the eventual callback..

    listenSock = CkSocket_Create();

    // Listen at the port indicated by the redirect_uri above.
    backLog = 5;
    success = CkSocket_BindAndListen(listenSock,3017,backLog);
    if (success != TRUE) {
        printf("%s\n",CkSocket_lastErrorText(listenSock));
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        return;
    }

    // Wait for the browser's connection in a background thread.
    // (We'll send load the URL into the browser following this..)
    // Wait a max of 60 seconds before giving up.
    maxWaitMs = 60000;
    task = CkSocket_AcceptNextConnectionAsync(listenSock,maxWaitMs);
    CkTask_Run(task);

    // -------------------------------------------------------------------
    // At this point, your application should load the URL in a browser.
    // You'll need to add code here to do it..

    // For example, 
    // in C#: System.Diagnostics.Process.Start(url);
    // in Java: Desktop.getDesktop().browse(new URI(url));
    // in VBScript: Set wsh=WScript.CreateObject("WScript.Shell")
    //              wsh.Run url
    // in Xojo: ShowURL(url)  (see http://docs.xojo.com/index.php/ShowURL)
    // in Dataflex: Runprogram Background "c:\Program Files\Internet Explorer\iexplore.exe" sUrl        
    // The account owner would interactively accept or deny the authorization request.

    // Add the code to load the url in a web browser here...
    // Add the code to load the url in a web browser here...
    // Add the code to load the url in a web browser here...
    // System.Diagnostics.Process.Start(url);

    // -------------------------------------------------------------------

    // Wait for the listenSock's task to complete.
    success = CkTask_Wait(task,maxWaitMs);
    if (!success || (CkTask_getStatusInt(task) != 7) || (CkTask_getTaskSuccess(task) != TRUE)) {
        if (!success) {
            // The task.LastErrorText applies to the Wait method call.
            printf("%s\n",CkTask_lastErrorText(task));
        }
        else {
            // The ResultErrorText applies to the underlying task method call (i.e. the AcceptNextConnection)
            printf("%s\n",CkTask_status(task));
            printf("%s\n",CkTask_resultErrorText(task));
        }

        CkTask_Dispose(task);
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        return;
    }

    // If we get to this point, a connection on listenSock was accepted, and the redirected POST
    // is waiting to be read on the connected socket.
    // The POST we are going to read contains the following:

    // POST /myapp/ HTTP/1.1
    // Host: localhost
    // Content-Type: application/x-www-form-urlencoded
    // 
    // id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345

    // But first.. we no longer need the listen socket...
    // Stop listening on port 3017.
    CkSocket_Close(listenSock,10);

    // Get the connected socket.
    sock = CkSocket_Create();
    CkSocket_LoadTaskResult(sock,task);
    CkTask_Dispose(task);

    // We're acting as a temporary web server to receive this one redirected HTTP request..
    // Read the start line of the request.. (i.e. the "POST /myapp/ HTTP/1.1")
    startLine = CkSocket_receiveUntilMatch(sock,"\r\n");
    if (CkSocket_getLastMethodSuccess(sock) != TRUE) {
        printf("%s\n",CkSocket_lastErrorText(sock));
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        CkSocket_Dispose(sock);
        return;
    }

    // Read the request header.
    requestHeader = CkSocket_receiveUntilMatch(sock,"\r\n\r\n");
    if (CkSocket_getLastMethodSuccess(sock) != TRUE) {
        printf("%s\n",CkSocket_lastErrorText(sock));
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        CkSocket_Dispose(sock);
        return;
    }

    printf("%s\n",requestHeader);
    printf("----\n");

    // Read the body.
    // The body will contain "id_token= eyJ......"
    sbRequestBody = CkStringBuilder_Create();
    success = CkSocket_ReceiveSb(sock,sbRequestBody);
    if (success == FALSE) {
        printf("%s\n",CkSocket_lastErrorText(sock));
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        CkSocket_Dispose(sock);
        CkStringBuilder_Dispose(sbRequestBody);
        return;
    }

    printf("%s\n",CkStringBuilder_getAsString(sbRequestBody));

    // Given that we're acting as a web server, we must send a response..
    // We can now send our HTTP response.
    sbResponseHtml = CkStringBuilder_Create();
    CkStringBuilder_Append(sbResponseHtml,"<html><body><p>Thank you!</b></body</html>");

    sbResponse = CkStringBuilder_Create();
    CkStringBuilder_Append(sbResponse,"HTTP/1.1 200 OK\r\n");
    CkStringBuilder_Append(sbResponse,"Content-Length: ");
    CkStringBuilder_AppendInt(sbResponse,CkStringBuilder_getLength(sbResponseHtml));
    CkStringBuilder_Append(sbResponse,"\r\n");
    CkStringBuilder_Append(sbResponse,"Content-Type: text/html\r\n");
    CkStringBuilder_Append(sbResponse,"\r\n");
    CkStringBuilder_AppendSb(sbResponse,sbResponseHtml);

    CkSocket_SendString(sock,CkStringBuilder_getAsString(sbResponse));
    CkSocket_Close(sock,50);

    // Get the id_token from the sbRequestBody that we just received.
    // (Remember, we're acting as the web server, thus we received the redirect request..)
    hashTab = CkHashtable_Create();
    CkHashtable_AddQueryParams(hashTab,CkStringBuilder_getAsString(sbRequestBody));

    // See https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens#validating-an-id-token
    // for more information about ID tokens..
    idToken = CkHashtable_lookupStr(hashTab,"id_token");

    jwt = CkJwt_Create();

    // Let's see if the time constraints, if any, are valid.
    // The above JWT was created on the afternoon of 16-May-2016, with an expiration of 1 hour.
    // If the current system time is before the "nbf" time, or after the "exp" time,
    // then IsTimeValid will return false/0.
    // Also, we'll allow a leeway of 60 seconds to account for any clock skew.
    // Note: If the token has no "nbf" or "exp" claim fields, then IsTimeValid is always true.
    leeway = 60;
    bTimeValid = CkJwt_IsTimeValid(jwt,idToken,leeway);
    printf("time constraints valid: %d\n",bTimeValid);

    // Now let's recover the original claims JSON (the payload).
    payload = CkJwt_getPayload(jwt,idToken);
    // The payload will likely be in compact form:
    printf("%s\n",payload);

    // We can format for human viewing by loading it into Chilkat's JSON object
    // and emit.
    json = CkJsonObject_Create();
    success = CkJsonObject_Load(json,payload);
    CkJsonObject_putEmitCompact(json,FALSE);
    printf("%s\n",CkJsonObject_emit(json));

    // Sample output:

    // {
    //   "aud": "f125d695-c50e-456e-a579-a486f06d1213",
    //   "iss": "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/v2.0",
    //   "iat": 1626535322,
    //   "nbf": 1626535322,
    //   "exp": 1626539222,
    //   "aio": "AWQAm/8TAAAAHQncmY0VvhgyMIhfleHX3DjsGfmlPM1CopkJ3mPnBUnCxrJ0ubruaACEhwGO7NsoHBhqFEzRzPxOq7MtuGVFsql+qJKZx8vQCszKYEPX9Wb3b5+d5KJTABHCIH48bTFd",
    //   "idp": "https://sts.windows.net/9188040d-6c67-4c5b-b112-36a304b66dad/",
    //   "nonce": "1519043321",
    //   "rh": "0.ARgAZt2NbdFosEOvXOMbS33VzZXWJfEOxW5FpXmkhvBtEhMYALQ.",
    //   "sub": "RMIZlHJ7hfsJmL8Qq3h6M0nPi4g-HEavnAFgxzaT2KM",
    //   "tid": "6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd",
    //   "uti": "-BXGHxvfREW-r9HI5NBiAA",
    //   "ver": "2.0"
    // }

    // We can recover the original JOSE header in the same way:
    joseHeader = CkJwt_getHeader(jwt,idToken);
    // The payload will likely be in compact form:
    printf("%s\n",joseHeader);

    // We can format for human viewing by loading it into Chilkat's JSON object
    // and emit.
    jsonJoseHeader = CkJsonObject_Create();
    success = CkJsonObject_Load(jsonJoseHeader,joseHeader);
    CkJsonObject_putEmitCompact(jsonJoseHeader,FALSE);
    printf("%s\n",CkJsonObject_emit(jsonJoseHeader));

    // Sample output:

    // {
    //   "typ": "JWT",
    //   "alg": "RS256",
    //   "kid": "nOo3ZDrODXEK1jKWhXslHR_KXEg"
    // }

    // Finally, we need to fetch the JSON Web Key Sets from the jwks_uri
    // and use it to verify the id_token's RSA signature.
    sbJwks = CkStringBuilder_Create();
    http = CkHttp_Create();
    success = CkHttp_QuickGetSb(http,jwks_uri,sbJwks);
    if (success == FALSE) {
        printf("%s\n",CkHttp_lastErrorText(http));
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        CkSocket_Dispose(sock);
        CkStringBuilder_Dispose(sbRequestBody);
        CkStringBuilder_Dispose(sbResponseHtml);
        CkStringBuilder_Dispose(sbResponse);
        CkHashtable_Dispose(hashTab);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(json);
        CkJsonObject_Dispose(jsonJoseHeader);
        CkStringBuilder_Dispose(sbJwks);
        CkHttp_Dispose(http);
        return;
    }

    jwkset = CkJsonObject_Create();
    success = CkJsonObject_LoadSb(jwkset,sbJwks);
    CkJsonObject_putEmitCompact(jwkset,FALSE);
    printf("%s\n",CkJsonObject_emit(jwkset));

    // A sample jwkset:

    // {
    //   "keys": [
    //     {
    //       "kty": "RSA",
    //       "use": "sig",
    //       "kid": "nOo3ZDrODXEK1jKWhXslHR_KXEg",
    //       "x5t": "nOo3ZDrODXEK1jKWhXslHR_KXEg",
    //       "n": "oaLLT9hkcSj ... NVrZdUdTBQ",
    //       "e": "AQAB",
    //       "x5c": [
    //         "MIIDBTC ... MRku44Dw7R"
    //       ],
    //       "issuer": "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/v2.0"
    //     },
    //     {
    //       "kty": "RSA",
    //       "use": "sig",
    //       "kid": "l3sQ-50cCH4xBVZLHTGwnSR7680",
    //       "x5t": "l3sQ-50cCH4xBVZLHTGwnSR7680",
    //       "n": "sfsXMXW ... AYkwb6xUQ",
    //       "e": "AQAB",
    //       "x5c": [
    //         "MIIDBTCCA ... BWrh+/vJ"
    //       ],
    //       "issuer": "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/v2.0"
    //     },
    //     {
    //       "kty": "RSA",
    //       "use": "sig",
    //       "kid": "DqUu8gf-nAgcyjP3-SuplNAXAnc",
    //       "x5t": "DqUu8gf-nAgcyjP3-SuplNAXAnc",
    //       "n": "1n7-nWSL ... V3pFWhQ",
    //       "e": "AQAB",
    //       "x5c": [
    //         "MIIC8TC ... 9pIcnkPQ=="
    //       ],
    //       "issuer": "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/v2.0"
    //     },
    //     {
    //       "kty": "RSA",
    //       "use": "sig",
    //       "kid": "OzZ5Dbmcso9Qzt2ModGmihg30Bo",
    //       "x5t": "OzZ5Dbmcso9Qzt2ModGmihg30Bo",
    //       "n": "01re9a2BU ... 5OzQ6Q",
    //       "e": "AQAB",
    //       "x5c": [
    //         "MIIC8TC ... YmwJ6sDdRvQ=="
    //       ],
    //       "issuer": "https://login.microsoftonline.com/6d8ddd66-68d1-43b0-af5c-e31b4b7dd5cd/v2.0"
    //     }
    //   ]
    // }

    // We should have an RSA key with kid matching the kid from the joseHeader..
    kid = CkJsonObject_stringOf(jsonJoseHeader,"kid");

    // Find the RSA key with the specified key id
    jwk = CkJsonObject_FindRecord(jwkset,"keys","kid",kid,TRUE);
    if (CkJsonObject_getLastMethodSuccess(jwkset) == FALSE) {
        printf("Failed to find a matching RSA key in the JWK key set...\n");
        CkHttpRequest_Dispose(req);
        CkPrng_Dispose(prng);
        CkStringBuilder_Dispose(sbUrl);
        CkSocket_Dispose(listenSock);
        CkSocket_Dispose(sock);
        CkStringBuilder_Dispose(sbRequestBody);
        CkStringBuilder_Dispose(sbResponseHtml);
        CkStringBuilder_Dispose(sbResponse);
        CkHashtable_Dispose(hashTab);
        CkJwt_Dispose(jwt);
        CkJsonObject_Dispose(json);
        CkJsonObject_Dispose(jsonJoseHeader);
        CkStringBuilder_Dispose(sbJwks);
        CkHttp_Dispose(http);
        CkJsonObject_Dispose(jwkset);
        return;
    }

    pubkey = CkPublicKey_Create();

    success = CkPublicKey_LoadFromString(pubkey,CkJsonObject_emit(jwk));
    if (success == FALSE) {
        printf("%s\n",CkPublicKey_lastErrorText(pubkey));
        printf("%s\n",CkJsonObject_emit(jwk));
    }
    else {
        verified = CkJwt_VerifyJwtPk(jwt,idToken,pubkey);
        printf("Verified: %d\n",verified);
    }

    CkJsonObject_Dispose(jwk);


    CkHttpRequest_Dispose(req);
    CkPrng_Dispose(prng);
    CkStringBuilder_Dispose(sbUrl);
    CkSocket_Dispose(listenSock);
    CkSocket_Dispose(sock);
    CkStringBuilder_Dispose(sbRequestBody);
    CkStringBuilder_Dispose(sbResponseHtml);
    CkStringBuilder_Dispose(sbResponse);
    CkHashtable_Dispose(hashTab);
    CkJwt_Dispose(jwt);
    CkJsonObject_Dispose(json);
    CkJsonObject_Dispose(jsonJoseHeader);
    CkStringBuilder_Dispose(sbJwks);
    CkHttp_Dispose(http);
    CkJsonObject_Dispose(jwkset);
    CkPublicKey_Dispose(pubkey);

    }

 

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