Last active
August 18, 2021 18:57
-
-
Save renant/a3ebc838de3527d559556d2795a6b76b to your computer and use it in GitHub Desktop.
Example to validate firebase token in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System; | |
using System.Collections.Generic; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Security.Claims; | |
using System.Security.Cryptography.X509Certificates; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.IdentityModel.Tokens; | |
namespace ConsoleApp2 | |
{ | |
class Program | |
{ | |
static HttpClient client = new HttpClient(); | |
static void Main() | |
{ | |
string encodedJwt = "TOKEN"; | |
string firebaseProjectId = "FIREBASEID"; | |
RunAsync(encodedJwt, firebaseProjectId).Wait(); | |
Console.ReadKey(); | |
} | |
static async Task RunAsync(string encodedJwt, string firebaseProjectId) | |
{ | |
// 1. Get Google signing keys | |
client.BaseAddress = new Uri("https://www.googleapis.com/robot/v1/metadata/"); | |
var response = await client.GetAsync("x509/[email protected]"); | |
if (!response.IsSuccessStatusCode) { return; } | |
var x509Data = await response.Content.ReadAsAsync<Dictionary<string, string>>(); | |
var keys = x509Data.Values.Select(CreateSecurityKeyFromPublicKey).ToArray(); | |
// 2. Configure validation parameters | |
var parameters = new TokenValidationParameters | |
{ | |
ValidIssuer = "https://securetoken.google.com/" + firebaseProjectId, | |
ValidAudience = firebaseProjectId, | |
IssuerSigningKeys = keys, | |
}; | |
// 3. Use JwtSecurityTokenHandler to validate signature, issuer, audience and lifetime | |
var handler = new JwtSecurityTokenHandler(); | |
var principal = handler.ValidateToken(encodedJwt, parameters, out var token); | |
var jwt = (JwtSecurityToken)token; | |
// 4.Validate signature algorithm and other applicable valdiations | |
if (jwt.Header.Alg != SecurityAlgorithms.RsaSha256) | |
{ | |
throw new SecurityTokenInvalidSignatureException( | |
"The token is not signed with the expected algorithm."); | |
} | |
foreach (var claim in principal.Claims) | |
{ | |
Console.WriteLine($"{claim.Type}::{claim.Value}"); | |
} | |
var teste = principal.Claims.Where(x => x.Type == "user_id").Select(x => x.Value).FirstOrDefault(); | |
Console.WriteLine(teste); | |
} | |
static SecurityKey CreateSecurityKeyFromPublicKey(string data) | |
{ | |
return new X509SecurityKey(new X509Certificate2(Encoding.UTF8.GetBytes(data))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment