Skip to content

Instantly share code, notes, and snippets.

@spasiu
Last active July 10, 2024 19:32
Show Gist options
  • Save spasiu/2432ffd32698d97ba78ecc763b8e4048 to your computer and use it in GitHub Desktop.
Save spasiu/2432ffd32698d97ba78ecc763b8e4048 to your computer and use it in GitHub Desktop.
Generate a Zendesk Messaging JWT in .Net and login the user on the client side.
zE("messenger", "loginUser", (callback) => callback(token));
using System;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Text;
public class JwtTokenGenerator
{
public string CreateZendeskJwtToken(string zendeskSecret, string keyId, string userName, string userEmail, string externalId)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(zendeskSecret));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var header = new JwtHeader(credentials);
//keyId is required by Zendesk - need to generate from wagepoint admin interface + secret
//Zendesk messaging SDK requires name, email, external_id, and scope
header.Add("kid", keyId);
// Add required claims
var payload = new JwtPayload
{
{"name", userName},
{"email", userEmail},
{"external_id", externalId},
{"scope", "user"},
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
{ "exp", DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() } // Token expiry time
//can add more claims as necessary
};
// Create the JWT token
var token = new JwtSecurityToken(header, payload);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment