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

PureBasic 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

 

 

 

(PureBasic) 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 PureBasic Module Download

Chilkat PureBasic Module

IncludeFile "CkJsonObject.pb"
IncludeFile "CkJwt.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkJsonArray.pb"
IncludeFile "CkCrypt2.pb"
IncludeFile "CkHttpRequest.pb"
IncludeFile "CkHttpResponse.pb"
IncludeFile "CkCert.pb"
IncludeFile "CkStringBuilder.pb"

Procedure ChilkatExample()

    ; 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.i = CkCert::ckCreate()
    If cert.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkCert::setCkVerboseLogging(cert, 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.
    success.i = CkCert::ckLoadPfxFile(cert,"qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret")
    If success = 0
        Debug CkCert::ckLastErrorText(cert)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    privKey.i = CkCert::ckExportPrivateKey(cert)
    If CkCert::ckLastMethodSuccess(cert) = 0
        Debug CkCert::ckLastErrorText(cert)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    jwt.i = CkJwt::ckCreate()
    If jwt.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Build the JOSE header
    jose.i = CkJsonObject::ckCreate()
    If jose.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
    success = CkJsonObject::ckAppendString(jose,"alg","RS256")
    success = CkJsonObject::ckAppendString(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.s = "99999999-aaaa-bbbb-cccc-ddddeeeeffff"

    claims.i = CkJsonObject::ckCreate()
    If claims.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    crypt.i = CkCrypt2::ckCreate()
    If crypt.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::ckAppendString(claims,"jti",CkCrypt2::ckGenerateUuid(crypt))
    CkJsonObject::ckAppendString(claims,"sub",myClientId)

    ; Set the timestamp of when the JWT was created to now minus 60 seconds
    curDateTime.i = CkJwt::ckGenNumericDate(jwt,-60)
    success = CkJsonObject::ckAddIntAt(claims,-1,"iat",curDateTime)

    ; Set the "not process before" timestamp to now minus 60 seconds
    success = CkJsonObject::ckAddIntAt(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::ckAddIntAt(claims,-1,"exp",curDateTime + 3600)

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

    ; Produce the smallest possible JWT:
    CkJwt::setCkAutoCompact(jwt, 1)

    ; Create the JWT token.  This is where the RSA signature is created.
    jwt_token.s = CkJwt::ckCreateJwtPk(jwt,CkJsonObject::ckEmit(jose),CkJsonObject::ckEmit(claims),privKey)

    Debug jwt_token

    ; Step 2 ------------------------------------------------------------------------------------------
    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Fetch the discovery document...
    resp.i = CkHttp::ckQuickRequest(http,"GET","https://test-login.unieconomy.no/.well-known/openid-configuration")
    If CkHttp::ckLastMethodSuccess(http) <> 1
        Debug CkHttp::ckLastErrorText(http)
        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        ProcedureReturn
    EndIf

    If CkHttpResponse::ckStatusCode(resp) <> 200
        Debug "Received response status code " + Str(CkHttpResponse::ckStatusCode(resp))
        Debug "Response body containing error text or JSON:"
        Debug CkHttpResponse::ckBodyStr(resp)
        CkHttpResponse::ckDispose(resp)

        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        ProcedureReturn
    EndIf

    json.i = CkJsonObject::ckCreate()
    If json.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(json,CkHttpResponse::ckBodyStr(resp))
    CkHttpResponse::ckDispose(resp)

    CkJsonObject::setCkEmitCompact(json, 0)
    Debug CkJsonObject::ckEmit(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.s = CkJsonObject::ckStringOf(json,"token_endpoint")

    grantTypes.i = CkJsonObject::ckArrayOf(json,"grant_types_supported")
    clientCredentialsIdx.i = CkJsonArray::ckFindString(grantTypes,"client_credentials",1)
    CkJsonArray::ckDispose(grantTypes)

    ; If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
    If clientCredentialsIdx < 0
        Debug "The client credentials grant type is not supported."
        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(json)
        ProcedureReturn
    EndIf

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

    req.i = CkHttpRequest::ckCreate()
    If req.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHttpRequest::setCkHttpVerb(req, "POST")
    CkHttpRequest::ckAddParam(req,"client_id",myClientId)
    CkHttpRequest::ckAddParam(req,"scope","AppFramework.Sales")
    CkHttpRequest::ckAddParam(req,"grant_type","client_credentials")
    CkHttpRequest::ckAddParam(req,"client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
    CkHttpRequest::ckAddParam(req,"client_assertion",jwt_token)

    resp = CkHttp::ckPostUrlEncoded(http,tokenEndpoint,req)
    If CkHttp::ckLastMethodSuccess(http) = 0
        Debug CkHttp::ckLastErrorText(http)
        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(json)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    ; Make sure we got a 200 response status code, otherwise it's an error.
    If CkHttpResponse::ckStatusCode(resp) <> 200
        Debug "POST to token endpoint failed."
        Debug "Received response status code " + Str(CkHttpResponse::ckStatusCode(resp))
        Debug "Response body containing error text or JSON:"
        Debug CkHttpResponse::ckBodyStr(resp)
        CkHttpResponse::ckDispose(resp)

        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(json)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(json,CkHttpResponse::ckBodyStr(resp))
    CkHttpResponse::ckDispose(resp)

    Debug CkJsonObject::ckEmit(json)

    ; The JSON response will look like this:

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

    ; Get the access token:
    accessToken.s = CkJsonObject::ckStringOf(json,"access_token")
    Debug "accessToken = " + 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::setCkAuthToken(http, accessToken)

    sbResponse.i = CkStringBuilder::ckCreate()
    If sbResponse.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkHttp::ckQuickGetSb(http,"https://test.unieconomy.no/api/init/companies",sbResponse)
    If success = 0
        Debug CkHttp::ckLastErrorText(http)
        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(json)
        CkHttpRequest::ckDispose(req)
        CkStringBuilder::ckDispose(sbResponse)
        ProcedureReturn
    EndIf

    ; Examine the response status code.
    If CkHttp::ckLastStatus(http) <> 200
        Debug CkStringBuilder::ckGetAsString(sbResponse)
        Debug "response status: " + Str(CkHttp::ckLastStatus(http))
        Debug "Received error response."
        CkCert::ckDispose(cert)
        CkJwt::ckDispose(jwt)
        CkJsonObject::ckDispose(jose)
        CkJsonObject::ckDispose(claims)
        CkCrypt2::ckDispose(crypt)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(json)
        CkHttpRequest::ckDispose(req)
        CkStringBuilder::ckDispose(sbResponse)
        ProcedureReturn
    EndIf

    CkJsonObject::ckLoadSb(json,sbResponse)
    Debug CkJsonObject::ckEmit(json)

    Debug "Success."


    CkCert::ckDispose(cert)
    CkJwt::ckDispose(jwt)
    CkJsonObject::ckDispose(jose)
    CkJsonObject::ckDispose(claims)
    CkCrypt2::ckDispose(crypt)
    CkHttp::ckDispose(http)
    CkJsonObject::ckDispose(json)
    CkHttpRequest::ckDispose(req)
    CkStringBuilder::ckDispose(sbResponse)


    ProcedureReturn
EndProcedure

 

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