Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.Extensions.Configuration;
namespace ZendeskJWT.Controllers
{
[Authorize]
public class HomeController : Controller
{
private IConfiguration configuration;
private string SUBDOMAIN => "YOUR_ZENDESK_SUBDOMAIN";
private string SHARED_KEY => "YOUR_ZENDESK_SHARED_KEY";
public IActionResult Index()
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int timestamp = (int)t.TotalSeconds;
var email = HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();
var payload = new Dictionary<string, object>() {
{ "alg" , "HS256"},
{ "typ", "JWT" },
{ "iat", timestamp },
{ "jti", Guid.NewGuid().ToString() },
{ "name", HttpContext.User.Identity.Name },
{ "email", email }
};
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string token = encoder.Encode(payload, SHARED_KEY);
string redirectUrl = "https://" + SUBDOMAIN + ".zendesk.com/access/jwt?jwt=" + token;
string returnTo = HttpContext.Request.Query["return_to"].ToString();
if (returnTo != null)
{
redirectUrl += "&return_to=" + HttpUtility.UrlEncode(returnTo);
}
return Redirect(redirectUrl);
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.