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

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

 

 

 

(Unicode C) Box.com OAuth2 with JSON Web Tokens

See more Box Examples

Demonstrates how to obtain an OAuth2 access token using a JSON Web Token. The following explanation is copied from Box Authentication Models

OAuth2 with JSON Web Tokens enables an application to connect directly to Box and obtain authorization to access files and folders without requiring users to log in. Using OAuth2 with JSON Web Tokens an application can provide Box features without users even being aware that Box exists.

Instead of requiring the user to log in to Box, the application generates JSON Web Token (JWT) verified by an RSA keypair. If this authentication succeeds then the application obtains an access token that grants authorization to operate on Box files and folders. This machine-to-machine authentication replaces the first leg of the three-legged authentication process defined by OAuth2, and enables users of your application to work with Box content without seeing Box login requests.

OAuth2 with JSON Web Tokens is designed to be used with Box Platform. You can use OAuth2 with JWT with both Service Accounts and App Users.

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_CkJsonObjectW.h>
#include <C_CkPrivateKeyW.h>
#include <C_CkJwtW.h>
#include <C_CkPrngW.h>
#include <C_CkRestW.h>

void ChilkatSample(void)
    {
    HCkJsonObjectW jsonRsaKey;
    BOOL success;
    const wchar_t *passphrase;
    const wchar_t *privateKeyPem;
    HCkPrivateKeyW rsaKey;
    HCkJwtW jwt;
    HCkJsonObjectW jose;
    HCkJsonObjectW claims;
    HCkPrngW prng;
    HCkRestW rest;
    BOOL bAutoReconnect;
    const wchar_t *jsonResponse;
    HCkJsonObjectW jResponse;
    const wchar_t *accessToken;

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

    // When you created an RSA key pair using the Box web user interface,
    // you downloaded a json file named something like "7152782_kkdxptq2_config.json"
    // This contains the following:

    // {
    //   "boxAppSettings": {
    //     "clientID": "0kraci84o0jfr7yuw596tf394iigzbe7",
    //     "clientSecret": "xxxxxxxxxxxxxxxxxxxxxxxxx",
    //     "appAuth": {
    //       "publicKeyID": "kkdxptq2",
    //       "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDj ... nceU=\n-----END ENCRYPTED PRIVATE KEY-----\n",
    //       "passphrase": "xxxxxxxxxxxxxxxxxxxxxxxx"
    //     }
    //   },
    //   "enterpriseID": "7152782"
    // }
    // 

    // Load it into a Chilkat JSON object to allow access to the content.
    jsonRsaKey = CkJsonObjectW_Create();
    success = CkJsonObjectW_LoadFile(jsonRsaKey,L"qa_data/tokens/7152782_kkdxptq2_config.json");

    // Load the private key into a Chilkat private key object.
    passphrase = CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.appAuth.passphrase");
    privateKeyPem = CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.appAuth.privateKey");

    rsaKey = CkPrivateKeyW_Create();
    success = CkPrivateKeyW_LoadEncryptedPem(rsaKey,privateKeyPem,passphrase);
    if (success != TRUE) {
        wprintf(L"%s\n",CkPrivateKeyW_lastErrorText(rsaKey));
        CkJsonObjectW_Dispose(jsonRsaKey);
        CkPrivateKeyW_Dispose(rsaKey);
        return;
    }

    // The JSON Web Token will be created using the JWT class
    jwt = CkJwtW_Create();

    // Construct the JOSE header...
    jose = CkJsonObjectW_Create();
    // Chilkat supports the following algorithms: "RS256", "RS384", and "RS512".  (Chilkat also supports other algorithms that Box does not yet support.)
    CkJsonObjectW_UpdateString(jose,L"alg",L"RS256");
    CkJsonObjectW_UpdateString(jose,L"typ",L"JWT");
    CkJsonObjectW_UpdateString(jose,L"kid",CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.appAuth.publicKeyID"));

    // Now let's build the JWT claims. Most of this is just boilerplate (i.e. the same every time..)
    // The JWT claims contain these required and optional elements:

    // iss (required, String)  The Client ID of the service that created the JWT assertion.
    // sub (required, String)  enterprise_id for a token specific to an enterprise when creating and managing app users, or the app user_id for a token specific to an individual app user.
    // box_sub_type (required, String)  "enterprise" or "user" depending on the type of token being requested in the sub claim.
    // aud (required, String) Always "https://api.box.com/oauth2/token" for OAuth2 token requests
    // jti (required, String) A universally unique identifier specified by the client for this JWT. This is a unique string that is at least 16 characters and at most 128 characters.
    // exp (required, NumericDate) The unix time as to when this JWT will expire. This can be set to a maximum value of 60 seconds beyond the issue time. Note: It is recommended to set this value to less than the maximum allowed 60 seconds.
    // iat (optional, NumericDate) Issued at time. The token cannot be used before this time.
    // nbf (optional, NumericDate) Not before. Specifies when the token will start being valid.
    // 

    claims = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(claims,L"iss",CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.clientID"));
    CkJsonObjectW_UpdateString(claims,L"sub",CkJsonObjectW_stringOf(jsonRsaKey,L"enterpriseID"));
    CkJsonObjectW_UpdateString(claims,L"box_sub_type",L"enterprise");
    CkJsonObjectW_UpdateString(claims,L"aud",L"https://api.box.com/oauth2/token");

    // Generate 32 random bytes (base64 encoded) for the "jti"
    prng = CkPrngW_Create();
    CkJsonObjectW_UpdateString(claims,L"jti",CkPrngW_genRandom(prng,32,L"base64"));

    // Set the expiration time to 60 seconds after the current time.
    CkJsonObjectW_UpdateInt(claims,L"exp",CkJwtW_GenNumericDate(jwt,60));

    // We're going to do the following POST to get a JSON response that contains our OAuth2 access token:

    // 	POST /oauth2/token
    // 	Content-Type: application/x-www-form-urlencoded
    // 	grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&
    // 	assertion=<JWT>&
    // 	client_id=<client_id>&
    // 	client_secret=<client_secret>

    // First, make the initial connection.
    // A single REST object, once connected, can be used for many Box REST API calls.
    // The auto-reconnect indicates that if the already-established HTTPS connection is closed,
    // then it will be automatically re-established as needed.
    rest = CkRestW_Create();
    bAutoReconnect = TRUE;
    success = CkRestW_Connect(rest,L"api.box.com",443,TRUE,bAutoReconnect);
    if (success != TRUE) {
        wprintf(L"%s\n",CkRestW_lastErrorText(rest));
        CkJsonObjectW_Dispose(jsonRsaKey);
        CkPrivateKeyW_Dispose(rsaKey);
        CkJwtW_Dispose(jwt);
        CkJsonObjectW_Dispose(jose);
        CkJsonObjectW_Dispose(claims);
        CkPrngW_Dispose(prng);
        CkRestW_Dispose(rest);
        return;
    }

    // Add the query params.
    // Calling ClearAllParts is wise if previous requests were sent prior to this one on the same REST object..
    CkRestW_ClearAllParts(rest);
    CkRestW_AddQueryParam(rest,L"grant_type",L"urn:ietf:params:oauth:grant-type:jwt-bearer");
    CkRestW_AddQueryParam(rest,L"client_id",CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.clientID"));
    CkRestW_AddQueryParam(rest,L"client_secret",CkJsonObjectW_stringOf(jsonRsaKey,L"boxAppSettings.clientSecret"));
    CkRestW_AddQueryParam(rest,L"assertion",CkJwtW_createJwtPk(jwt,CkJsonObjectW_emit(jose),CkJsonObjectW_emit(claims),rsaKey));

    jsonResponse = CkRestW_fullRequestFormUrlEncoded(rest,L"POST",L"/oauth2/token");
    if (CkRestW_getLastMethodSuccess(rest) != TRUE) {
        wprintf(L"%s\n",CkRestW_lastErrorText(rest));
        CkJsonObjectW_Dispose(jsonRsaKey);
        CkPrivateKeyW_Dispose(rsaKey);
        CkJwtW_Dispose(jwt);
        CkJsonObjectW_Dispose(jose);
        CkJsonObjectW_Dispose(claims);
        CkPrngW_Dispose(prng);
        CkRestW_Dispose(rest);
        return;
    }

    // If successful, we'll get a response status code equal to 200,
    // and a JSON response that looks like this:

    // 	{
    // 	   "access_token": "mNr1FrCvOeWiGnwLL0OcTL0Lux5jbyBa",
    // 	   "expires_in": 4169,
    // 	   "restricted_to": [],
    // 	   "token_type": "bearer"
    // 	}
    // 

    jResponse = CkJsonObjectW_Create();
    CkJsonObjectW_putEmitCompact(jResponse,FALSE);
    CkJsonObjectW_Load(jResponse,jsonResponse);

    if (CkRestW_getResponseStatusCode(rest) != 200) {
        wprintf(L"%s\n",CkJsonObjectW_emit(jResponse));
        wprintf(L"Failed.\n");
        CkJsonObjectW_Dispose(jsonRsaKey);
        CkPrivateKeyW_Dispose(rsaKey);
        CkJwtW_Dispose(jwt);
        CkJsonObjectW_Dispose(jose);
        CkJsonObjectW_Dispose(claims);
        CkPrngW_Dispose(prng);
        CkRestW_Dispose(rest);
        CkJsonObjectW_Dispose(jResponse);
        return;
    }

    wprintf(L"%s\n",CkJsonObjectW_emit(jResponse));

    // Get the access token:
    accessToken = CkJsonObjectW_stringOf(jResponse,L"access_token");
    wprintf(L"Access token, valid for 60 minutes: %s\n",accessToken);


    CkJsonObjectW_Dispose(jsonRsaKey);
    CkPrivateKeyW_Dispose(rsaKey);
    CkJwtW_Dispose(jwt);
    CkJsonObjectW_Dispose(jose);
    CkJsonObjectW_Dispose(claims);
    CkPrngW_Dispose(prng);
    CkRestW_Dispose(rest);
    CkJsonObjectW_Dispose(jResponse);

    }

 

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