Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Validate JSON Web Token (JWT) With .NET JWT Library
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace kendo_board.Authentication {
public class TokenValidator {
static Lazy<Dictionary<string, X509Certificate2>> Certificates = new Lazy<Dictionary<string, X509Certificate2>>(FetchGoogleCertificates);
public static Lazy<Dictionary<string, X509Certificate2>> Certificates1 {
get {
return Certificates;
set {
Certificates = value;
static Dictionary<string, X509Certificate2> FetchGoogleCertificates() {
using (var http = new HttpClient()) {
var json = http.GetStringAsync("").Result;
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
return dictionary.ToDictionary(x => x.Key, x => new X509Certificate2(Encoding.UTF8.GetBytes(x.Value)));
static public JwtSecurityToken ValidateIdentityToken(string idToken) {
var token = new JwtSecurityToken(idToken);
var jwtHandler = new JwtSecurityTokenHandler();
var certificates = Certificates1.Value;
try {
// Set up token validation
var tokenValidationParameters = new TokenValidationParameters();
tokenValidationParameters.ValidAudience = ConfigurationManager.AppSettings.Get("GoogleClientID");
tokenValidationParameters.ValidIssuer = "";
tokenValidationParameters.IssuerSigningTokens = certificates.Values.Select(x => new X509SecurityToken(x));
tokenValidationParameters.IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x));
tokenValidationParameters.IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
return identifier.Select(x =>
if (!certificates.ContainsKey(x.Id))
return null;
return new X509SecurityKey(certificates[x.Id]);
}).First(x => x != null);
SecurityToken jwt;
var claimsPrincipal = jwtHandler.ValidateToken(idToken, tokenValidationParameters, out jwt);
return (JwtSecurityToken)jwt;
catch {
return null;

This comment has been minimized.

Copy link

commented May 10, 2017


This comment has been minimized.

Copy link

commented Sep 21, 2018

Can you summarize in one sentence what it means to validate a JWT?

I mean in a mathematical way, I don't care about terminology like "secure" "privacy" or "authenticity".

Is it something like a pure function

validate(signed_token, certificate) -> true|false

which returns true iff there is a token such that

signed_token == someWayToSignAToken(token, certificate)


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.