Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

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

local cert = chilkat.Cert.new()
cert.verbose_logging = true
-- Note: .pfx and .p12 files are identical.  The only difference is the file extension.
local success = cert:load_pfx_file("qa_data/pfx/UniCert_Norge_Test_secret.pfx", "secret")
if not success then
    print(cert.last_error_text)
    return
end

local privKey = chilkat.PrivateKey.new()
success = cert:get_private_key(privKey)
if not success then
    print(cert.last_error_text)
    return
end

local jwt = chilkat.Jwt.new()

-- Build the JOSE header
local jose = chilkat.JsonObject.new()
-- Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
success = jose:append_string("alg", "RS256")
success = jose:append_string("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.
local myClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff"

local claims = chilkat.JsonObject.new()
local crypt = chilkat.Crypt2.new()
claims:append_string("jti", crypt:generate_uuid())
claims:append_string("sub", myClientId)

-- Set the timestamp of when the JWT was created to now minus 60 seconds
local curDateTime = jwt:gen_numeric_date(-60)
success = claims:add_int_at(-1, "iat", curDateTime)

-- Set the "not process before" timestamp to now minus 60 seconds
success = claims:add_int_at(-1, "nbf", curDateTime)

-- Set the timestamp defining an expiration time (end time) for the token
-- to be now + 1 hour (3600 seconds)
success = claims:add_int_at(-1, "exp", curDateTime + 3600)

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

-- Produce the smallest possible JWT:
jwt.auto_compact = true

-- Create the JWT token.  This is where the RSA signature is created.
local jwt_token = jwt:create_jwt_pk(jose:emit(), claims:emit(), privKey)

print(jwt_token)

-- Step 2 ------------------------------------------------------------------------------------------
local http = chilkat.Http.new()

-- Fetch the discovery document...
local resp = chilkat.HttpResponse.new()
success = http:http_no_body("GET", "https://test-login.unieconomy.no/.well-known/openid-configuration", resp)
if not success then
    print(http.last_error_text)
    return
end

if resp.status_code ~= 200 then
    print("Received response status code " .. resp.status_code)
    print("Response body containing error text or JSON:")
    print(resp.body_str)
    return
end

local json = chilkat.JsonObject.new()
success = json:load(resp.body_str)

json.emit_compact = false
print(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.

local tokenEndpoint = json:string_of("token_endpoint")

local grantTypes = json:array_of("grant_types_supported")
local clientCredentialsIdx = grantTypes:find_string("client_credentials", true)

-- If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
if clientCredentialsIdx < 0 then
    print("The client credentials grant type is not supported.")
    return
end

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

local req = chilkat.HttpRequest.new()
req.http_verb = "POST"
req.content_type = "application/x-www-form-urlencoded"

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

success = http:http_req(tokenEndpoint, req, resp)
if not success then
    print(http.last_error_text)
    return
end

-- Make sure we got a 200 response status code, otherwise it's an error.
if resp.status_code ~= 200 then
    print("POST to token endpoint failed.")
    print("Received response status code " .. resp.status_code)
    print("Response body containing error text or JSON:")
    print(resp.body_str)
    return
end

success = json:load(resp.body_str)

print(json:emit())

-- The JSON response will look like this:

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

-- Get the access token:
local accessToken = json:string_of("access_token")
print("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.
http.auth_token = accessToken

local sbResponse = chilkat.StringBuilder.new()
success = http:quick_get_sb("https://test.unieconomy.no/api/init/companies", sbResponse)
if not success then
    print(http.last_error_text)
    return
end

-- Examine the response status code.
if http.last_status ~= 200 then
    print(sbResponse:get_as_string())
    print("response status: " .. http.last_status)
    print("Received error response.")
    return
end

json:load_sb(sbResponse)
print(json:emit())

print("Success.")