【发布时间】:2016-11-06 09:17:10
【问题描述】:
我正在尝试使用自定义令牌实现 Firebase 3 身份验证机制(如 https://firebase.google.com/docs/auth/server/create-custom-tokens 中所述)。
我的服务器是 ASP.NET MVC 应用程序。
因此,根据说明 (https://firebase.google.com/docs/server/setup),我为我的 Firebase 应用程序创建了一个服务帐户,并生成了一个“.p12”格式的密钥。
之后,根据此处的说明 (https://firebase.google.com/docs/auth/server/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library),我尝试生成自定义令牌并使用上一步收到的密钥对其进行签名。对于令牌生成,我使用了 Microsoft 的 SystemIdentityModel.Tokens.Jwt 库,因此代码如下所示:
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var key = new X509AsymmetricSecurityKey(new X509Certificate2(p12path, p12pwd));
var signinCredentials = new SigningCredentials(key, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#rsa-sha256");
Int32 nowInUnixTimestamp = (Int32)(now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
var token = tokenHandler.CreateToken(
issuer: serviceAccountEmail,
audience: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
signingCredentials: signinCredentials,
subject: new ClaimsIdentity(new Claim[]
{
new Claim("sub", serviceAccountEmail),
new Claim("iat", nowInUnixTimestamp.ToString()),
new Claim("exp", (nowInUnixTimestamp + (60*60)).ToString()),
new Claim("uid", uid)
})
);
var tokenString = tokenHandler.WriteToken(token);
然后尝试使用 Firebase Javascript SDK 在 React Native 应用程序中登录用户,代码如下:
//omitting initialization code
firebase.auth().signInWithCustomToken(firebaseJWT).catch(function(error) {
console.log('Error authenticating Firebase user. Code: ' + error.code + ' Message: ' + error.message);
});
但从 Firebase 收到错误消息:
对 Firebase 用户进行身份验证时出错。代码:auth/invalid-custom-token 消息:自定义令牌格式不正确。请检查文档。
尝试为令牌过期控制添加不同的声明也无济于事。
我还尝试使用“dvsekhvalnov/jose-jwt”库生成令牌,但无法使用“RS256”算法。
那么问题来了:
关于我做错了什么有什么建议吗?
【问题讨论】:
-
我意识到链接stackoverflow.com/questions/37408684/…描述的token格式是Firebase自己发布的token,所以第一个问题不再是问题了。
-
这是 Google 支持人员对同一问题的回答:“我在 SO 中看到您的帖子,您已经有了解决方法。对于令牌格式,您应该始终关注最新消息最新的文档。目前在身份验证方面存在一些问题,我们正在尽最大努力让事情顺利进行。请留意我们的发行说明以获取任何进一步的更新,并随时与我们联系如果需要。” 因此,目前看来解决方法是最好的选择。
标签: c# asp.net-mvc firebase firebase-authentication