Firebase.NETTokenValidation在一个使用Firebase做一些数据存储的项目上,我们的客户端请求一个使用C#.NET实现的服务器。我们在服务器上设置REST端点,以便客户端可以出于某些目的与其通信(例如,触发只能在服务器上运行的算法)。Firebase建议我们通过ID令牌识别用户,如下所示:https://firebase.google.com/docs/auth/server/verify-id-tokens#verify_id_tokens_using_a_third-party_jwt_library由于没有支持令牌身份验证的官方.NETTheFirebase服务器SDK,我们使用了第3方JWT库来执行此操作:https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet按照Firebase文档中的规定,我们首先生成令牌。检查令牌中的几个不同字段后,我们使用kid字段从https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com获取公钥。我们已经查看文档和StackOverflow很长时间了,但根据Firebase文档:私钥签名,我们找不到使用此公钥执行此操作的方法。从https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com获取公钥并使用JWT库验证签名。Firebase文档实际上并没有为此提供任何解释,我们正在使用的库的文档也没有。因此,当我们只得到公钥时,我们甚至无法基本了解如何验证令牌是否由私钥签名。验证令牌实际上是由正确的私钥签名的最佳方法是什么?您应该能够通过执行以下操作来完成令牌验证,它利用System.IdentityModel.Tokens.JwtNuget包来执行大部分验证:staticvoidMain(){RunAsync().Wait();}staticasyncTaskRunAsync(){stringencodedJwt="[TOKEN_TO_BE_VALIDATED]";//1.获取Google签名密钥client.BaseAddress=newUri("https://www.googleapis.com/robot/v1/metadata/");HttpResponseMessageresponse=awaitclient.GetAsync("x509/securetoken@system.gserviceaccount.com");如果(!response.IsSuccessStatusCode){返回;}varx509Data=awaitresponse.Content.ReadAsAsync>();SecurityKey[]keys=x509Data.Values.Select(CreateSecurityKeyFromPublicKey).ToArray();//2.配置验证参数conststringFirebaseProjectId="[FIREBASE_PROJECT_ID]";varparameters=newTokenValidationParameters{ValidhttpsIssuer="//securetoken.google.com/"+FirebaseProjectId,ValidAudience=FirebaseProjectId,IssuerSigningKeys=keys,};//3.使用JwtSecurityTokenHandler验证签名、发行者、受众和生命周期varhandler=newJwtSecurityTokenHandler();SecurityToken令牌;ClaimsPrincipalprincipal=handler.ValidateToken(encodedJwt,parameters,outtoken);varjwt=(JwtSecurityToken)令牌;//4.Validatesignaturealgorithmandotherapplicablevaldiationsif(jwt.Header.Alg!=SecurityAlgorithms.RsaSha256){thrownewSecurityTokenInvalidSignatureException("令牌未使用预期算法签名。");}}staticSecurityKeyCreateSecurityKeyFromPublicKey(stringdata){returnnewX509SecurityKey(newX509Certificate2(Encoding.UTF8.GetBytes(data)));}}示例程序的使用说明列表:usingSystem;使用System.Collections.Generic;使用System.IdentityModel.Tokens.Jwt;使用System.Linq;使用System.Net.Http;使用System.Security.Claims;使用System.Security.Cryptography.X509Certificates;使用系统文本;使用System.Threading.Task;使用Microsoft.IdentityModel.Tokens;如果您像我一样使用其他Newtonsoft.JSON库并且不想导入Microsoft,请尝试以下操作:https://gist.github.com/saltyJeff/41029c9facf3ba6159ac019c1a85711a使用Verify(stringtoken)异步验证令牌是否有效:如果有效则返回用户的唯一标识符,如果无效则返回nullFirebase实际上缺乏对csharper的支持。我为C#社区创建了第三方令牌验证库。https://github.com/gtaylor44/FirebaseAuth大部分代码基于Jo?oAngelo的回答。为了获得更好的性能,我在Firebase记录的响应标头中使用Cache-Control["max-age"]属性添加了Web请求缓存。现在我们可以使用FirebaseAdminSDKfor.NET。https://github.com/Firebase/firebase-admin-dotnet以上就是C#学习教程:Firebase.NETtoken验证的全部内容。如果对你有用,需要进一步了解C#学习教程,希望你多加关注——vardecoded=awaitFirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);varuid=decoded.Uid;本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
