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

PowerBuilder 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

 

 

 

(PowerBuilder) 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 ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

integer li_rc
oleobject loo_Cert
integer li_Success
oleobject loo_PrivKey
oleobject loo_Jwt
oleobject loo_Jose
string ls_MyClientId
oleobject loo_Claims
oleobject loo_Crypt
integer li_CurDateTime
string ls_Jwt_token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Json
string ls_TokenEndpoint
oleobject loo_GrantTypes
integer li_ClientCredentialsIdx
oleobject loo_Req
string ls_AccessToken
oleobject loo_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...

loo_Cert = create oleobject
// Use "Chilkat_9_5_0.Cert" for versions of Chilkat < 10.0.0
li_rc = loo_Cert.ConnectToNewObject("Chilkat.Cert")
if li_rc < 0 then
    destroy loo_Cert
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Cert.VerboseLogging = 1
// 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.
li_Success = loo_Cert.LoadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret")
if li_Success = 0 then
    Write-Debug loo_Cert.LastErrorText
    destroy loo_Cert
    return
end if

loo_PrivKey = loo_Cert.ExportPrivateKey()
if loo_Cert.LastMethodSuccess = 0 then
    Write-Debug loo_Cert.LastErrorText
    destroy loo_Cert
    return
end if

loo_Jwt = create oleobject
// Use "Chilkat_9_5_0.Jwt" for versions of Chilkat < 10.0.0
li_rc = loo_Jwt.ConnectToNewObject("Chilkat.Jwt")

// Build the JOSE header
loo_Jose = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_Jose.ConnectToNewObject("Chilkat.JsonObject")

// Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
li_Success = loo_Jose.AppendString("alg","RS256")
li_Success = loo_Jose.AppendString("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.
ls_MyClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff"

loo_Claims = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_Claims.ConnectToNewObject("Chilkat.JsonObject")

loo_Crypt = create oleobject
// Use "Chilkat_9_5_0.Crypt2" for versions of Chilkat < 10.0.0
li_rc = loo_Crypt.ConnectToNewObject("Chilkat.Crypt2")

loo_Claims.AppendString("jti",loo_Crypt.GenerateUuid())
loo_Claims.AppendString("sub",ls_MyClientId)

// Set the timestamp of when the JWT was created to now minus 60 seconds
li_CurDateTime = loo_Jwt.GenNumericDate(-60)
li_Success = loo_Claims.AddIntAt(-1,"iat",li_CurDateTime)

// Set the "not process before" timestamp to now minus 60 seconds
li_Success = loo_Claims.AddIntAt(-1,"nbf",li_CurDateTime)

// Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
li_Success = loo_Claims.AddIntAt(-1,"exp",li_CurDateTime + 3600)

loo_Claims.AppendString("iss",ls_MyClientId)
loo_Claims.AppendString("aud","https://test-login.unieconomy.no/connect/token")

// Produce the smallest possible JWT:
loo_Jwt.AutoCompact = 1

// Create the JWT token.  This is where the RSA signature is created.
ls_Jwt_token = loo_Jwt.CreateJwtPk(loo_Jose.Emit(),loo_Claims.Emit(),loo_PrivKey)

Write-Debug ls_Jwt_token

// Step 2 ------------------------------------------------------------------------------------------
loo_Http = create oleobject
// Use "Chilkat_9_5_0.Http" for versions of Chilkat < 10.0.0
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")

// Fetch the discovery document...
loo_Resp = loo_Http.QuickRequest("GET","https://test-login.unieconomy.no/.well-known/openid-configuration")
if loo_Http.LastMethodSuccess <> 1 then
    Write-Debug loo_Http.LastErrorText
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    return
end if

if loo_Resp.StatusCode <> 200 then
    Write-Debug "Received response status code " + string(loo_Resp.StatusCode)
    Write-Debug "Response body containing error text or JSON:"
    Write-Debug loo_Resp.BodyStr
    destroy loo_Resp
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    return
end if

loo_Json = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Json.Load(loo_Resp.BodyStr)
destroy loo_Resp

loo_Json.EmitCompact = 0
Write-Debug loo_Json.Emit()

// 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.

ls_TokenEndpoint = loo_Json.StringOf("token_endpoint")

loo_GrantTypes = loo_Json.ArrayOf("grant_types_supported")
li_ClientCredentialsIdx = loo_GrantTypes.FindString("client_credentials",1)
destroy loo_GrantTypes

// If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
if li_ClientCredentialsIdx < 0 then
    Write-Debug "The client credentials grant type is not supported."
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    destroy loo_Json
    return
end if

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

loo_Req = create oleobject
// Use "Chilkat_9_5_0.HttpRequest" for versions of Chilkat < 10.0.0
li_rc = loo_Req.ConnectToNewObject("Chilkat.HttpRequest")

loo_Req.HttpVerb = "POST"
loo_Req.AddParam("client_id",ls_MyClientId)
loo_Req.AddParam("scope","AppFramework.Sales")
loo_Req.AddParam("grant_type","client_credentials")
loo_Req.AddParam("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
loo_Req.AddParam("client_assertion",ls_Jwt_token)

loo_Resp = loo_Http.PostUrlEncoded(ls_TokenEndpoint,loo_Req)
if loo_Http.LastMethodSuccess = 0 then
    Write-Debug loo_Http.LastErrorText
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    destroy loo_Json
    destroy loo_Req
    return
end if

// Make sure we got a 200 response status code, otherwise it's an error.
if loo_Resp.StatusCode <> 200 then
    Write-Debug "POST to token endpoint failed."
    Write-Debug "Received response status code " + string(loo_Resp.StatusCode)
    Write-Debug "Response body containing error text or JSON:"
    Write-Debug loo_Resp.BodyStr
    destroy loo_Resp
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    destroy loo_Json
    destroy loo_Req
    return
end if

li_Success = loo_Json.Load(loo_Resp.BodyStr)
destroy loo_Resp

Write-Debug loo_Json.Emit()

// The JSON response will look like this:

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

// Get the access token:
ls_AccessToken = loo_Json.StringOf("access_token")
Write-Debug "accessToken = " + ls_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.
loo_Http.AuthToken = ls_AccessToken

loo_SbResponse = create oleobject
// Use "Chilkat_9_5_0.StringBuilder" for versions of Chilkat < 10.0.0
li_rc = loo_SbResponse.ConnectToNewObject("Chilkat.StringBuilder")

li_Success = loo_Http.QuickGetSb("https://test.unieconomy.no/api/init/companies",loo_SbResponse)
if li_Success = 0 then
    Write-Debug loo_Http.LastErrorText
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    destroy loo_Json
    destroy loo_Req
    destroy loo_SbResponse
    return
end if

// Examine the response status code.
if loo_Http.LastStatus <> 200 then
    Write-Debug loo_SbResponse.GetAsString()
    Write-Debug "response status: " + string(loo_Http.LastStatus)
    Write-Debug "Received error response."
    destroy loo_Cert
    destroy loo_Jwt
    destroy loo_Jose
    destroy loo_Claims
    destroy loo_Crypt
    destroy loo_Http
    destroy loo_Json
    destroy loo_Req
    destroy loo_SbResponse
    return
end if

loo_Json.LoadSb(loo_SbResponse)
Write-Debug loo_Json.Emit()

Write-Debug "Success."


destroy loo_Cert
destroy loo_Jwt
destroy loo_Jose
destroy loo_Claims
destroy loo_Crypt
destroy loo_Http
destroy loo_Json
destroy loo_Req
destroy loo_SbResponse

 

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