Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.0.0+

Uni Economy API Client Credentials Flow

See more OAuth2 Examples

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

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCert
LOCAL oPrivKey
LOCAL oJwt
LOCAL oJose
LOCAL cMyClientId
LOCAL oClaims
LOCAL oCrypt
LOCAL nCurDateTime
LOCAL cJwt_token
LOCAL oHttp
LOCAL oResp
LOCAL oJson
LOCAL cTokenEndpoint
LOCAL oGrantTypes
LOCAL nClientCredentialsIdx
LOCAL oReq
LOCAL cAccessToken
LOCAL oSbResponse

nSuccess := 0

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

oCert := CreateObject("Chilkat.Cert")
oCert: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.
nSuccess := oCert:LoadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx", "secret")
IF (nSuccess == 0)
    ? oCert:LastErrorText
    oCert:destroy()
    RETURN
ENDIF

oPrivKey := CreateObject("Chilkat.PrivateKey")
nSuccess := oCert:GetPrivateKey(oPrivKey)
IF (nSuccess == 0)
    ? oCert:LastErrorText
    oCert:destroy()
    oPrivKey:destroy()
    RETURN
ENDIF

oJwt := CreateObject("Chilkat.Jwt")

//  Build the JOSE header
oJose := CreateObject("Chilkat.JsonObject")
//  Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
nSuccess := oJose:AppendString("alg", "RS256")
nSuccess := oJose: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.
cMyClientId := "99999999-aaaa-bbbb-cccc-ddddeeeeffff"

oClaims := CreateObject("Chilkat.JsonObject")
oCrypt := CreateObject("Chilkat.Crypt2")
oClaims:AppendString("jti", oCrypt:GenerateUuid())
oClaims:AppendString("sub", cMyClientId)

//  Set the timestamp of when the JWT was created to now minus 60 seconds
nCurDateTime := oJwt:GenNumericDate(-60)
nSuccess := oClaims:AddIntAt(-1, "iat", nCurDateTime)

//  Set the "not process before" timestamp to now minus 60 seconds
nSuccess := oClaims:AddIntAt(-1, "nbf", nCurDateTime)

//  Set the timestamp defining an expiration time (end time) for the token
//  to be now + 1 hour (3600 seconds)
nSuccess := oClaims:AddIntAt(-1, "exp", nCurDateTime + 3600)

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

//  Produce the smallest possible JWT:
oJwt:AutoCompact := 1

//  Create the JWT token.  This is where the RSA signature is created.
cJwt_token := oJwt:CreateJwtPk(oJose:Emit(), oClaims:Emit(), oPrivKey)

? cJwt_token

//  Step 2 ------------------------------------------------------------------------------------------
oHttp := CreateObject("Chilkat.Http")

//  Fetch the discovery document...
oResp := CreateObject("Chilkat.HttpResponse")
nSuccess := oHttp:HttpNoBody("GET", "https://test-login.unieconomy.no/.well-known/openid-configuration", oResp)
IF (nSuccess == 0)
    ? oHttp:LastErrorText
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    RETURN
ENDIF

IF (oResp:StatusCode != 200)
    ? "Received response status code " + Str(oResp:StatusCode)
    ? "Response body containing error text or JSON:"
    ? oResp:BodyStr
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    RETURN
ENDIF

oJson := CreateObject("Chilkat.JsonObject")
nSuccess := oJson:Load(oResp:BodyStr)

oJson:EmitCompact := 0
? oJson: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.

cTokenEndpoint := oJson:StringOf("token_endpoint")

oGrantTypes := oJson:ArrayOf("grant_types_supported")
nClientCredentialsIdx := oGrantTypes:FindString("client_credentials", 1)
oGrantTypes:destroy()

//  If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
IF (nClientCredentialsIdx < 0)
    ? "The client credentials grant type is not supported."
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    oJson:destroy()
    RETURN
ENDIF

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

oReq := CreateObject("Chilkat.HttpRequest")
oReq:HttpVerb := "POST"
oReq:ContentType := "application/x-www-form-urlencoded"

oReq:AddParam("client_id", cMyClientId)
oReq:AddParam("scope", "AppFramework.Sales")
oReq:AddParam("grant_type", "client_credentials")
oReq:AddParam("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
oReq:AddParam("client_assertion", cJwt_token)

nSuccess := oHttp:HttpReq(cTokenEndpoint, oReq, oResp)
IF (nSuccess == 0)
    ? oHttp:LastErrorText
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    oJson:destroy()
    oReq:destroy()
    RETURN
ENDIF

//  Make sure we got a 200 response status code, otherwise it's an error.
IF (oResp:StatusCode != 200)
    ? "POST to token endpoint failed."
    ? "Received response status code " + Str(oResp:StatusCode)
    ? "Response body containing error text or JSON:"
    ? oResp:BodyStr
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    oJson:destroy()
    oReq:destroy()
    RETURN
ENDIF

nSuccess := oJson:Load(oResp:BodyStr)

? oJson:Emit()

//  The JSON response will look like this:

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

//  Get the access token:
cAccessToken := oJson:StringOf("access_token")
? "accessToken = " + cAccessToken

//  ------------------------------------------------------
//  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.
oHttp:AuthToken := cAccessToken

oSbResponse := CreateObject("Chilkat.StringBuilder")
nSuccess := oHttp:QuickGetSb("https://test.unieconomy.no/api/init/companies", oSbResponse)
IF (nSuccess == 0)
    ? oHttp:LastErrorText
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    oJson:destroy()
    oReq:destroy()
    oSbResponse:destroy()
    RETURN
ENDIF

//  Examine the response status code.
IF (oHttp:LastStatus != 200)
    ? oSbResponse:GetAsString()
    ? "response status: " + Str(oHttp:LastStatus)
    ? "Received error response."
    oCert:destroy()
    oPrivKey:destroy()
    oJwt:destroy()
    oJose:destroy()
    oClaims:destroy()
    oCrypt:destroy()
    oHttp:destroy()
    oResp:destroy()
    oJson:destroy()
    oReq:destroy()
    oSbResponse:destroy()
    RETURN
ENDIF

oJson:LoadSb(oSbResponse)
? oJson:Emit()

? "Success."

oCert:destroy()
oPrivKey:destroy()
oJwt:destroy()
oJose:destroy()
oClaims:destroy()
oCrypt:destroy()
oHttp:destroy()
oResp:destroy()
oJson:destroy()
oReq:destroy()
oSbResponse:destroy()