Unicode C
Unicode C
Create JWT using a Certificate's Private Key
See more JSON Web Token (JWT) Examples
Demonstrates how to create a JWT using a certificate's private key.Chilkat Unicode C Downloads
#include <C_CkCertW.h>
#include <C_CkJwtW.h>
#include <C_CkJsonObjectW.h>
void ChilkatSample(void)
{
BOOL success;
HCkCertW cert;
HCkJwtW jwt;
HCkJsonObjectW jose;
HCkJsonObjectW claims;
int curDateTime;
const wchar_t *token;
success = FALSE;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Demonstrates how to create a JWT using an certificate's private key.
cert = CkCertW_Create();
// Load an ECC private key from a PEM file.
success = CkCertW_LoadPfxFile(cert,L"c:/temp/myPfx.pfx",L"pfxPassword");
if (success != TRUE) {
wprintf(L"%s\n",CkCertW_lastErrorText(cert));
CkCertW_Dispose(cert);
return;
}
jwt = CkJwtW_Create();
// Build the JOSE header
jose = CkJsonObjectW_Create();
// Note: The IsEcdsa function was added in Chilkat v10.1.0
if (CkCertW_IsEcdsa(cert) == TRUE) {
// Use ES256. Pass the string "ES384" or "ES512" to use ECC with SHA-384 or SHA-512.
CkJsonObjectW_AppendString(jose,L"alg",L"ES256");
}
else {
// Probably RSA...
// Use RS256. Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
CkJsonObjectW_AppendString(jose,L"alg",L"RS256");
}
CkJsonObjectW_AppendString(jose,L"typ",L"JWT");
// Now build the JWT claims (also known as the payload)
claims = CkJsonObjectW_Create();
CkJsonObjectW_AppendString(claims,L"iss",L"http://example.org");
CkJsonObjectW_AppendString(claims,L"sub",L"John");
CkJsonObjectW_AppendString(claims,L"aud",L"http://example.com");
// Set the timestamp of when the JWT was created to now.
curDateTime = CkJwtW_GenNumericDate(jwt,0);
CkJsonObjectW_AddIntAt(claims,-1,L"iat",curDateTime);
// Set the "not process before" timestamp to now.
CkJsonObjectW_AddIntAt(claims,-1,L"nbf",curDateTime);
// Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
CkJsonObjectW_AddIntAt(claims,-1,L"exp",curDateTime + 3600);
// Produce the smallest possible JWT:
CkJwtW_putAutoCompact(jwt,TRUE);
// Create the JWT token.
token = CkJwtW_createJwtCert(jwt,CkJsonObjectW_emit(jose),CkJsonObjectW_emit(claims),cert);
wprintf(L"%s\n",token);
// Example output:
// eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vZXhhbXBsZS5vcmciLCJzdWIiOiJKb2huIiwiYXVkIjoiaHR0cDovL2V4YW1wbGUuY29tIiwiaWF0IjoxNDg1NzA4NzkyLCJuYmYiOjE0ODU3MDg3OTIsImV4cCI6MTQ4NTcxMjM5Mn0.wqsuyJpxJ073ox-lOiLFqG1lQocXe4hGf2XGZJRrO3qn0UusxI_bu3Gzky8gBsH4sA4u9TWZn5M-1wYMMIJk6Q
CkCertW_Dispose(cert);
CkJwtW_Dispose(jwt);
CkJsonObjectW_Dispose(jose);
CkJsonObjectW_Dispose(claims);
}