Skip to content

Instantly share code, notes, and snippets.

@JhonBv
Forked from renant/TokenFirebaseVerify.cs
Created March 25, 2021 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JhonBv/1e3664e1d62437e53256e80bafc9e5ae to your computer and use it in GitHub Desktop.
Save JhonBv/1e3664e1d62437e53256e80bafc9e5ae to your computer and use it in GitHub Desktop.
Example to validate firebase token in C#
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/securetoken@system.gserviceaccount.com");
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