Skip to content

Instantly share code, notes, and snippets.

@pwhe23
Last active May 25, 2021 18:09
Show Gist options
  • Select an option

  • Save pwhe23/d8b7a75fa57ebeb7fa19deaf2ad5971a to your computer and use it in GitHub Desktop.

Select an option

Save pwhe23/d8b7a75fa57ebeb7fa19deaf2ad5971a to your computer and use it in GitHub Desktop.
FreshDesk SSO using JWT with C#
// https://www.nuget.org/packages/JWT/
using JWT.Algorithms;
using JWT.Builder;
using Microsoft.AspNetCore.WebUtilities;
using System.Security.Cryptography;
class Program
{
void Main()
{
// Start by redirecting the browser to your FreshDesk {subdomain}:
// https://{subdomain}.freshdesk.com/customer/login
// Then Freshdesk will redirect back to your url with some required querystring values:
var uriFromFreshdeskRequest = "https://awesomecompany.com/sso/jwt/login?client_id=a13v13&state=hgdg43567&nonce=1545894408&grant_type=implicit&scope=profile+openid+email";
var query = QueryHelpers.ParseQuery(new Uri(uriFromFreshdeskRequest).Query);
var state = query["state"].ToString();
var nonce = query["nonce"].ToString();
// Generate RSA KEY
// * https://www.csfieldguide.org.nz/en/interactives/rsa-key-generator/
// * Parameters: 1024bits PKCS#8 (base(64)
// ImportFromPem will fail unless the IIS ApplicationPool has LoadUserProfile=true
using var privateKey = RSA.Create();
privateKey.ImportFromPem(@"
-----BEGIN PRIVATE KEY-----
{generate using url above}
-----END PRIVATE KEY-----
");
using var publicKey = RSA.Create();
publicKey.ImportFromPem(@"
-----BEGIN PUBLIC KEY-----
{generate using url above}
-----END PUBLIC KEY-----
");
var token = JwtBuilder
.Create()
.WithAlgorithm(new RS256Algorithm(publicKey, privateKey))
.AddClaims(new Dictionary<string, object>
{
{ "sub", "user id in your system" },
{ "email", "email" },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() },
{ "nonce", nonce },
{ "given_name", "firstname" },
{ "family_name", "lastname" },
{ "company", "organization" },
})
.Encode();
// The url to redirect to is provided by Freshdesk when signing up for sso and should resemble the one below
var url = QueryHelpers.AddQueryString("https://subdomain.freshworks.com/sp/OIDC/1234567890/implicit", new Dictionary<string, string?>
{
{"state", state},
{"id_token", token},
});
Console.WriteLine(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment