首页 > 解决方案 > JWT Fire base 验证 ID

问题描述

我已经复制了一个库来验证基于这个respo的 firebase 令牌。我的应用程序像后端一样使用 azure 函数,因此在用户登录后,每个操作都会使用令牌发送到 azure 函数,并且 azure 函数将验证该令牌然后响应结果。图书馆从这里获取公钥。我创建了一个天蓝色函数来测试这个库。我的请求:

var client = new RestClient("http://localhost:7071/api/test-connection");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("x-requested-with", "XMLHttpRequest");
request.AddHeader("Authorization", "Bearer <My Firebase Token>");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

我遇到了异常

IDX10516: Signature validation failed. Unable to match key: 
kid: 'System.String'.
Exceptions caught:
 'System.Text.StringBuilder'. 
token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'. Valid Lifetime: 'System.Boolean'. Valid Issuer: 'System.Boolean'

我花了两天多的时间研究原因和解决方案。一周前我的代码运行良好。问题是由我从谷歌获得的公钥引起的吗?

标签: c#firebase-authenticationjwt

解决方案


I was getting the same error, and was having a really hard time debugging it.

Based on this answer, I added the following code to my Startup.cs:

if (env.IsDevelopment())
{
     IdentityModelEventSource.ShowPII = true; 
}

Once I made this change and reproduced the error, I was able to see the actual value for kid (instead of kid: 'System.String' in my error message, I saw kid: 'ABCDEF' - not the real value, but hopefully you get the idea).

Next, I compared that value to the kid values listed here - and sure enough, that value was not present, hence the "unable to match key" error.

In my case, it turns out that I was not obtaining the token from Firebase correctly. I was making a request to https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword, but from the documentation I found this:

returnSecureToken boolean - Should always be true.

I was not setting this property in my request. After using a token obtained when setting this property correctly, I stopped getting the "IDX10516: Signature validation failed. Unable to match key" error in my C# code.


推荐阅读