Zig Requires Chilkat v11.0.0+
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// 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...
const cert = try chilkat.Cert.init();
defer cert.deinit();
cert.setVerboseLogging(true);
// 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.
cert.loadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx", "secret") catch {
std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
return;
};
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
cert.getPrivateKey(priv_key) catch {
std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
return;
};
const jwt = try chilkat.Jwt.init();
defer jwt.deinit();
// Build the JOSE header
const jose = try chilkat.JsonObject.init();
defer jose.deinit();
// Use RS256. Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
try jose.appendString("alg", "RS256");
try 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.
const my_client_id = "99999999-aaaa-bbbb-cccc-ddddeeeeffff";
const claims = try chilkat.JsonObject.init();
defer claims.deinit();
const crypt = try chilkat.Crypt2.init();
defer crypt.deinit();
claims.appendString("jti", try crypt.generateUuid(alloc)) catch {};
claims.appendString("sub", my_client_id) catch {};
// Set the timestamp of when the JWT was created to now minus 60 seconds
const cur_date_time = jwt.genNumericDate(-60);
try claims.addIntAt(-1, "iat", cur_date_time);
// Set the "not process before" timestamp to now minus 60 seconds
try claims.addIntAt(-1, "nbf", cur_date_time);
// Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
try claims.addIntAt(-1, "exp", cur_date_time + 3600);
claims.appendString("iss", my_client_id) catch {};
claims.appendString("aud", "https://test-login.unieconomy.no/connect/token") catch {};
// Produce the smallest possible JWT:
jwt.setAutoCompact(true);
// Create the JWT token. This is where the RSA signature is created.
const jwt_token = try jwt.createJwtPk(alloc, try jose.emit(alloc), try claims.emit(alloc), priv_key);
std.debug.print("{s}\n", .{jwt_token});
// Step 2 ------------------------------------------------------------------------------------------
const http = try chilkat.Http.init();
defer http.deinit();
// Fetch the discovery document...
const resp = try chilkat.HttpResponse.init();
defer resp.deinit();
http.httpNoBody("GET", "https://test-login.unieconomy.no/.well-known/openid-configuration", resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
if (resp.getStatusCode() != 200) {
std.debug.print("Received response status code {d}\n", .{resp.getStatusCode()});
std.debug.print("Response body containing error text or JSON:\n", .{});
std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
return;
}
const json = try chilkat.JsonObject.init();
defer json.deinit();
try json.load(try resp.getBodyStr(alloc));
json.setEmitCompact(false);
std.debug.print("{s}\n", .{try json.emit(alloc)});
// 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.
const token_endpoint = try json.stringOf(alloc, "token_endpoint");
const grant_types = try json.arrayOf("grant_types_supported");
defer grant_types.deinit();
const client_credentials_idx = grant_types.findString("client_credentials", true);
// If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
if (client_credentials_idx < 0) {
std.debug.print("The client credentials grant type is not supported.\n", .{});
return;
}
// ------------------------------------------------------
// Request the access token using our Client ID and JWT
const req = try chilkat.HttpRequest.init();
defer req.deinit();
req.setHttpVerb("POST");
req.setContentType("application/x-www-form-urlencoded");
req.addParam("client_id", my_client_id);
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);
http.httpReq(token_endpoint, req, resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
// Make sure we got a 200 response status code, otherwise it's an error.
if (resp.getStatusCode() != 200) {
std.debug.print("POST to token endpoint failed.\n", .{});
std.debug.print("Received response status code {d}\n", .{resp.getStatusCode()});
std.debug.print("Response body containing error text or JSON:\n", .{});
std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
return;
}
try json.load(try resp.getBodyStr(alloc));
std.debug.print("{s}\n", .{try json.emit(alloc)});
// The JSON response will look like this:
// {
// "access_token": "...",
// "expires_in": 3600,
// "token_type": "Bearer",
// "scope": "AppFramework.Sales"
// }
// Get the access token:
const access_token = try json.stringOf(alloc, "access_token");
std.debug.print("accessToken = {s}\n", .{access_token});
// ------------------------------------------------------
// 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.setAuthToken(access_token);
const sb_response = try chilkat.StringBuilder.init();
defer sb_response.deinit();
http.quickGetSb("https://test.unieconomy.no/api/init/companies", sb_response) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
// Examine the response status code.
if (http.getLastStatus() != 200) {
std.debug.print("{s}\n", .{try sb_response.getAsString(alloc)});
std.debug.print("response status: {d}\n", .{http.getLastStatus()});
std.debug.print("Received error response.\n", .{});
return;
}
json.loadSb(sb_response) catch {};
std.debug.print("{s}\n", .{try json.emit(alloc)});
std.debug.print("Success.\n", .{});
}