Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

C# UWP/WinRT Examples

Web API Categories

ASN.1
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Azure Cloud Storage
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
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
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
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(C# UWP/WinRT) 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 Universal Windows Platform (UWP) / WinRT Downloads

Chilkat for the Universal Windows Platform (UWP)

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

Chilkat.Cert cert = new Chilkat.Cert();
cert.VerboseLogging = 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.
bool success = cert.LoadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret");
if (success == false) {
    Debug.WriteLine(cert.LastErrorText);
    return;
}

Chilkat.PrivateKey privKey = cert.ExportPrivateKey();
if (cert.LastMethodSuccess == false) {
    Debug.WriteLine(cert.LastErrorText);
    return;
}

Chilkat.Jwt jwt = new Chilkat.Jwt();

// Build the JOSE header
Chilkat.JsonObject jose = new 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.
string myClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff";

Chilkat.JsonObject claims = new Chilkat.JsonObject();
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
claims.AppendString("jti",crypt.GenerateUuid());
claims.AppendString("sub",myClientId);

// Set the timestamp of when the JWT was created to now minus 60 seconds
int 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);

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

// Produce the smallest possible JWT:
jwt.AutoCompact = true;

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

Debug.WriteLine(jwt_token);

// Step 2 ------------------------------------------------------------------------------------------
Chilkat.Http http = new Chilkat.Http();

// Fetch the discovery document...
Chilkat.HttpResponse resp = await http.QuickRequestAsync("GET","https://test-login.unieconomy.no/.well-known/openid-configuration");
if (http.LastMethodSuccess != true) {
    Debug.WriteLine(http.LastErrorText);
    return;
}

if (resp.StatusCode != 200) {
    Debug.WriteLine("Received response status code " + Convert.ToString(resp.StatusCode));
    Debug.WriteLine("Response body containing error text or JSON:");
    Debug.WriteLine(resp.BodyStr);

    return;
}

Chilkat.JsonObject json = new Chilkat.JsonObject();
success = json.Load(resp.BodyStr);

json.EmitCompact = false;
Debug.WriteLine(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.

string tokenEndpoint = json.StringOf("token_endpoint");

Chilkat.JsonArray grantTypes = json.ArrayOf("grant_types_supported");
int clientCredentialsIdx = grantTypes.FindString("client_credentials",true);

// If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found.
if (clientCredentialsIdx < 0) {
    Debug.WriteLine("The client credentials grant type is not supported.");
    return;
}

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

Chilkat.HttpRequest req = new Chilkat.HttpRequest();
req.HttpVerb = "POST";
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);

resp = await http.PostUrlEncodedAsync(tokenEndpoint,req);
if (http.LastMethodSuccess == false) {
    Debug.WriteLine(http.LastErrorText);
    return;
}

// Make sure we got a 200 response status code, otherwise it's an error.
if (resp.StatusCode != 200) {
    Debug.WriteLine("POST to token endpoint failed.");
    Debug.WriteLine("Received response status code " + Convert.ToString(resp.StatusCode));
    Debug.WriteLine("Response body containing error text or JSON:");
    Debug.WriteLine(resp.BodyStr);

    return;
}

success = json.Load(resp.BodyStr);

Debug.WriteLine(json.Emit());

// The JSON response will look like this:

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

// Get the access token:
string accessToken = json.StringOf("access_token");
Debug.WriteLine("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.AuthToken = accessToken;

Chilkat.StringBuilder sbResponse = new Chilkat.StringBuilder();
success = await http.QuickGetSbAsync("https://test.unieconomy.no/api/init/companies",sbResponse);
if (success == false) {
    Debug.WriteLine(http.LastErrorText);
    return;
}

// Examine the response status code.
if (http.LastStatus != 200) {
    Debug.WriteLine(sbResponse.GetAsString());
    Debug.WriteLine("response status: " + Convert.ToString(http.LastStatus));
    Debug.WriteLine("Received error response.");
    return;
}

json.LoadSb(sbResponse);
Debug.WriteLine(json.Emit());

Debug.WriteLine("Success.");

 

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