Skip to content

Instantly share code, notes, and snippets.

@mmorton
Forked from anonymous/TokenValidator.cs
Created October 23, 2015 02:35
Show Gist options
  • Save mmorton/1259b5edb12413ef457a to your computer and use it in GitHub Desktop.
Save mmorton/1259b5edb12413ef457a to your computer and use it in GitHub Desktop.
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;
}
}
}
}
@abomadi
Copy link

abomadi commented Mar 13, 2017

Hi, any idea why the lazy dictionary loading brings 3 certificates out of 4 from this uri https://www.googleapis.com/robot/v1/metadata/x509/[email protected]

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment