Chilkat HOME .NET Core C# Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi ActiveX Delphi DLL Go Java Lianja Mono C# Node.js Objective-C PHP ActiveX PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift 2 Swift 3,4,5... Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(Unicode C) Uni Economy API Client Credentials FlowDemonstrates 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
#include <C_CkCertW.h> #include <C_CkPrivateKeyW.h> #include <C_CkJwtW.h> #include <C_CkJsonObjectW.h> #include <C_CkCrypt2W.h> #include <C_CkHttpW.h> #include <C_CkHttpResponseW.h> #include <C_CkJsonArrayW.h> #include <C_CkHttpRequestW.h> #include <C_CkStringBuilderW.h> void ChilkatSample(void) { HCkCertW cert; BOOL success; HCkPrivateKeyW privKey; HCkJwtW jwt; HCkJsonObjectW jose; const wchar_t *myClientId; HCkJsonObjectW claims; HCkCrypt2W crypt; int curDateTime; const wchar_t *jwt_token; HCkHttpW http; HCkHttpResponseW resp; HCkJsonObjectW json; const wchar_t *tokenEndpoint; HCkJsonArrayW grantTypes; int clientCredentialsIdx; HCkHttpRequestW req; const wchar_t *accessToken; HCkStringBuilderW 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 = CkCertW_Create(); CkCertW_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 = CkCertW_LoadPfxFile(cert,L"qa_data/pfx/UniCert_Norge_Test_secret.pfx",L"secret"); if (success == FALSE) { wprintf(L"%s\n",CkCertW_lastErrorText(cert)); CkCertW_Dispose(cert); return; } privKey = CkCertW_ExportPrivateKey(cert); if (CkCertW_getLastMethodSuccess(cert) == FALSE) { wprintf(L"%s\n",CkCertW_lastErrorText(cert)); CkCertW_Dispose(cert); return; } jwt = CkJwtW_Create(); // Build the JOSE header jose = CkJsonObjectW_Create(); // Use RS256. Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512. success = CkJsonObjectW_AppendString(jose,L"alg",L"RS256"); success = CkJsonObjectW_AppendString(jose,L"typ",L"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 = L"99999999-aaaa-bbbb-cccc-ddddeeeeffff"; claims = CkJsonObjectW_Create(); crypt = CkCrypt2W_Create(); CkJsonObjectW_AppendString(claims,L"jti",CkCrypt2W_generateUuid(crypt)); CkJsonObjectW_AppendString(claims,L"sub",myClientId); // Set the timestamp of when the JWT was created to now minus 60 seconds curDateTime = CkJwtW_GenNumericDate(jwt,-60); success = CkJsonObjectW_AddIntAt(claims,-1,L"iat",curDateTime); // Set the "not process before" timestamp to now minus 60 seconds success = CkJsonObjectW_AddIntAt(claims,-1,L"nbf",curDateTime); // Set the timestamp defining an expiration time (end time) for the token // to be now + 1 hour (3600 seconds) success = CkJsonObjectW_AddIntAt(claims,-1,L"exp",curDateTime + 3600); CkJsonObjectW_AppendString(claims,L"iss",myClientId); CkJsonObjectW_AppendString(claims,L"aud",L"https://test-login.unieconomy.no/connect/token"); // Produce the smallest possible JWT: CkJwtW_putAutoCompact(jwt,TRUE); // Create the JWT token. This is where the RSA signature is created. jwt_token = CkJwtW_createJwtPk(jwt,CkJsonObjectW_emit(jose),CkJsonObjectW_emit(claims),privKey); wprintf(L"%s\n",jwt_token); // Step 2 ------------------------------------------------------------------------------------------ http = CkHttpW_Create(); // Fetch the discovery document... resp = CkHttpW_QuickRequest(http,L"GET",L"https://test-login.unieconomy.no/.well-known/openid-configuration"); if (CkHttpW_getLastMethodSuccess(http) != TRUE) { wprintf(L"%s\n",CkHttpW_lastErrorText(http)); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); 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)); CkHttpResponseW_Dispose(resp); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); return; } json = CkJsonObjectW_Create(); success = CkJsonObjectW_Load(json,CkHttpResponseW_bodyStr(resp)); CkHttpResponseW_Dispose(resp); CkJsonObjectW_putEmitCompact(json,FALSE); wprintf(L"%s\n",CkJsonObjectW_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 = 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"); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); CkJsonObjectW_Dispose(json); return; } // ------------------------------------------------------ // Request the access token using our Client ID and JWT req = CkHttpRequestW_Create(); CkHttpRequestW_putHttpVerb(req,L"POST"); CkHttpRequestW_AddParam(req,L"client_id",myClientId); CkHttpRequestW_AddParam(req,L"scope",L"AppFramework.Sales"); CkHttpRequestW_AddParam(req,L"grant_type",L"client_credentials"); CkHttpRequestW_AddParam(req,L"client_assertion_type",L"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); CkHttpRequestW_AddParam(req,L"client_assertion",jwt_token); resp = CkHttpW_PostUrlEncoded(http,tokenEndpoint,req); if (CkHttpW_getLastMethodSuccess(http) == FALSE) { wprintf(L"%s\n",CkHttpW_lastErrorText(http)); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); 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)); CkHttpResponseW_Dispose(resp); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); CkJsonObjectW_Dispose(json); CkHttpRequestW_Dispose(req); return; } success = CkJsonObjectW_Load(json,CkHttpResponseW_bodyStr(resp)); CkHttpResponseW_Dispose(resp); wprintf(L"%s\n",CkJsonObjectW_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 = CkJsonObjectW_stringOf(json,L"access_token"); wprintf(L"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. CkHttpW_putAuthToken(http,accessToken); sbResponse = CkStringBuilderW_Create(); success = CkHttpW_QuickGetSb(http,L"https://test.unieconomy.no/api/init/companies",sbResponse); if (success == FALSE) { wprintf(L"%s\n",CkHttpW_lastErrorText(http)); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); CkJsonObjectW_Dispose(json); CkHttpRequestW_Dispose(req); CkStringBuilderW_Dispose(sbResponse); return; } // Examine the response status code. if (CkHttpW_getLastStatus(http) != 200) { wprintf(L"%s\n",CkStringBuilderW_getAsString(sbResponse)); wprintf(L"response status: %d\n",CkHttpW_getLastStatus(http)); wprintf(L"Received error response.\n"); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); CkJsonObjectW_Dispose(json); CkHttpRequestW_Dispose(req); CkStringBuilderW_Dispose(sbResponse); return; } CkJsonObjectW_LoadSb(json,sbResponse); wprintf(L"%s\n",CkJsonObjectW_emit(json)); wprintf(L"Success.\n"); CkCertW_Dispose(cert); CkJwtW_Dispose(jwt); CkJsonObjectW_Dispose(jose); CkJsonObjectW_Dispose(claims); CkCrypt2W_Dispose(crypt); CkHttpW_Dispose(http); CkJsonObjectW_Dispose(json); CkHttpRequestW_Dispose(req); CkStringBuilderW_Dispose(sbResponse); } |
© 2000-2024 Chilkat Software, Inc. All Rights Reserved.