JSON Web Tokens (JWTs)
A JSON Web Token, or JWT, is an open standard for securely sharing information as a JSON object. JWTs are small enough to be used in a GET or POST parameter or an HTTP header, and because they are digitally signed, the information inside can be trusted.
JWTs can be generated using a library. Options can be found on JWT.io or GitHub.
Step 1: Collect the data object
Whether you are using a JWT with UTT or the Open Endpoints, you will need to start with the data object that you are trying to sign.
{
"id": "{id}",
"accountId": "{accountId}",
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"locale": "en_US",
"referralCode": "JOHNDOE"
}
Step 2: Assemble the JWT payload
The JWT payload structures the data trying to be signed in this format:
{
"user":{
"id": "{id}",
"accountId": "{accountId}",
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"locale": "en_US",
"referralCode": "JOHNDOE"
}
}
Step 3: Sign the payload
Use your chosen library to build the JWT with the payload, and sign it with your API key.
using System.Collections.Generic;
using System.Text;
using Jose;
namespace JWTExample
{
class Program
{
public static string buildJWT(string secret, string accountId, string userId, string email, string firstName, string lastName, long expiryDate, string referralCode)
{
var userPayload = new Dictionary<string, object>()
{
{ "id", userId },
{ "account", accountId },
{ "firstName", firstName },
{ "lastName", lastName },
{ "email", email },
{ "locale", locale },
{ "referralCode", referralCode }
};
var payload = new Dictionary<string, object<()
{
{ "user", userPayload },
{ "exp", expiryDate } //optional date in seconds since the epoch
};
//the encoding must match the encoding of your secret, UTF8 is just an example
var byteSecret = Encoding.UTF8.GetBytes(secret);
return Jose.JWT.Encode(payload, byteSecret, JwsAlgorithm.HS256);
}
}
}
require 'jwt'
def buildJWT(secret, userId, accountId, email, firstName, lastName, referralCode, locale, expiryDate)
secret = 'Referral SaaSquatch API key'
return payload = JWT.encode({
user: {
id: userId,
accountId: accountId,
firstName: firstName,
lastName: lastName,
email: email,
locale: locale,
referralCode: referralCode
},
exp: expiryDate #optional date in seconds since the epoch
}, secret)
end
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtExample {
public static String buildJwt(String keyId, String secret, Date expiryDate) {
// Build user object
final Map<String, Object> userMap = new HashMap<>();
userMap.put("id", "REPLACEME");
userMap.put("accountId", "REPLACEME");
userMap.put("firstName", "REPLACEME");
userMap.put("lastName", "REPLACEME");
userMap.put("email", "REPLACEME");
// Extra user fields, etc.
final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
.type(JOSEObjectType.JWT)
.keyID(keyId)
.build();
final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.claim("user", userMap)
// Not having an expiry works, but having an expiry is strongly recommended
.expirationTime(expiryDate)
.build();
final SignedJWT jwt = new SignedJWT(header, claimsSet);
try {
jwt.sign(new MACSigner(secret));
} catch (JOSEException e) {
// This will happen if your secret is shorter than 256 bits.
// If you are using your Impact API keys, you won't need to worry about it.
throw new RuntimeException(e);
}
return jwt.serialize();
}
}
use \\Firebase\\JWT\\JWT;
function buildJWT($secret, $userId, $accountId, $email, $firstName, $lastName, $locale, $referralCode) {
//build user object
$payload = array(
"user"; => array(
"id" => $userId,
"account" => $accountId,
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email,
"locale" => $locale,
"referralCode" => $referralCode,
),
"exp" => $expiryDate //optional date in seconds since the epoch
);
//the encoder defaults to HS256, no need to specify an algorithm
return JWT::encode($payload, $secret);
}
import jwt
def buildJWT(secret, userId, accountId, email, firstName, lastName, locale, referralCode, expiryDate):
return jwt.encode({
'user': {
'id': userId,
'accountId': accountId,
'firstName': firstName,
'lastName': lastName,
'email': email,
'locale': locale,
'referralCode': referralCode
},
'exp';: expiryDate #optional date in seconds since the epoch
}, secret, algorithm='HS256')
Step 4: Include the JWT with your calls
After creating a JWT, it must be included with all of your calls.
UTT
Here’s an example of how a UTT call that includes the JWT would appear:
<script>
window.squatchTenant = “TENANT_ALIAS”
window.squatchToken = “JWT_GOES_HERE”
</script>
<squatch-embed widget=”p/program-name/w/referrerWidget”></squatch-embed>
Open Endpoint API Call
For Open Endpoint API calls, the JWT must be included as a header with the key X-SaaSquatch-User-Token
. cURL uses the -H
flag to pass an extra header. You may specify any number of extra headers.
Note:
Open Endpoint API calls made from a server should be signed with your API key. Only Open Endpoint calls from a client should be signed with a JWT.
curl -X POST <https://app.referralsaasquatch.com/api/v1/{tenant_alias}/open/account/{accountId}/user/{userId}>
-H "X-SaaSquatch-User-Token: {X-SaaSquatch-User-Token}"
-H "Content-Type: application/json"
-d '{
"id": "7558cc3cf3dc01375d24f7c1070abb01cd979956",
"accountId": "7558cc3cf3dc01375d24f7c1070abb01cd979956",
"email": "[email protected]",
"firstName": "Joe",
"lastName": "Testerson",
"locale": "en_US",
"referralCode": "JOETESTERSON"
}'
Updated about 2 months ago