Sample code for 30+ languages & platforms
Classic ASP

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 Classic ASP Downloads

Classic ASP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 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...

set cert = Server.CreateObject("Chilkat.Cert")
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.
success = cert.LoadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret")
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( cert.LastErrorText) & "</pre>"
    Response.End
End If

set privKey = Server.CreateObject("Chilkat.PrivateKey")
success = cert.GetPrivateKey(privKey)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( cert.LastErrorText) & "</pre>"
    Response.End
End If

set jwt = Server.CreateObject("Chilkat.Jwt")

' Build the JOSE header
set jose = Server.CreateObject("Chilkat.JsonObject")
' Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
success = jose.AppendString("alg","RS256")
success = 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.
myClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff"

set claims = Server.CreateObject("Chilkat.JsonObject")
set crypt = Server.CreateObject("Chilkat.Crypt2")
success = claims.AppendString("jti",crypt.GenerateUuid())
success = claims.AppendString("sub",myClientId)

' Set the timestamp of when the JWT was created to now minus 60 seconds
curDateTime = jwt.GenNumericDate(-60)
success = claims.AddIntAt(-1,"iat",curDateTime)

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

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

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

' Produce the smallest possible JWT:
jwt.AutoCompact = 1

' Create the JWT token.  This is where the RSA signature is created.
jwt_token = jwt.CreateJwtPk(jose.Emit(),claims.Emit(),privKey)

Response.Write "<pre>" & Server.HTMLEncode( jwt_token) & "</pre>"

' Step 2 ------------------------------------------------------------------------------------------
set http = Server.CreateObject("Chilkat.Http")

' Fetch the discovery document...
set resp = Server.CreateObject("Chilkat.HttpResponse")
success = http.HttpNoBody("GET","https://test-login.unieconomy.no/.well-known/openid-configuration",resp)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
    Response.End
End If

If (resp.StatusCode <> 200) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Received response status code " & resp.StatusCode) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Response body containing error text or JSON:") & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( resp.BodyStr) & "</pre>"
    Response.End
End If

set json = Server.CreateObject("Chilkat.JsonObject")
success = json.Load(resp.BodyStr)

json.EmitCompact = 0
Response.Write "<pre>" & Server.HTMLEncode( json.Emit()) & "</pre>"

' 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 = json.StringOf("token_endpoint")

' grantTypes is a Chilkat.JsonArray
Set grantTypes = json.ArrayOf("grant_types_supported")
clientCredentialsIdx = grantTypes.FindString("client_credentials",1)

' If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
If (clientCredentialsIdx < 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( "The client credentials grant type is not supported.") & "</pre>"
    Response.End
End If

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

set req = Server.CreateObject("Chilkat.HttpRequest")
req.HttpVerb = "POST"
req.ContentType = "application/x-www-form-urlencoded"

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

success = http.HttpReq(tokenEndpoint,req,resp)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
    Response.End
End If

' Make sure we got a 200 response status code, otherwise it's an error.
If (resp.StatusCode <> 200) Then
    Response.Write "<pre>" & Server.HTMLEncode( "POST to token endpoint failed.") & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Received response status code " & resp.StatusCode) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Response body containing error text or JSON:") & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( resp.BodyStr) & "</pre>"
    Response.End
End If

success = json.Load(resp.BodyStr)

Response.Write "<pre>" & Server.HTMLEncode( json.Emit()) & "</pre>"

' The JSON response will look like this:

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

' Get the access token:
accessToken = json.StringOf("access_token")
Response.Write "<pre>" & Server.HTMLEncode( "accessToken = " & accessToken) & "</pre>"

' ------------------------------------------------------
' 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.AuthToken = accessToken

set sbResponse = Server.CreateObject("Chilkat.StringBuilder")
success = http.QuickGetSb("https://test.unieconomy.no/api/init/companies",sbResponse)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
    Response.End
End If

' Examine the response status code.
If (http.LastStatus <> 200) Then
    Response.Write "<pre>" & Server.HTMLEncode( sbResponse.GetAsString()) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "response status: " & http.LastStatus) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Received error response.") & "</pre>"
    Response.End
End If

success = json.LoadSb(sbResponse)
Response.Write "<pre>" & Server.HTMLEncode( json.Emit()) & "</pre>"

Response.Write "<pre>" & Server.HTMLEncode( "Success.") & "</pre>"

%>
</body>
</html>