Create a gist now

Instantly share code, notes, and snippets.

anonymous /TokenValidator.cs
Created Sep 21, 2015

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("https://www.googleapis.com/oauth2/v1/certs").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 = "accounts.google.com";
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment