gpt4 book ai didi

c# - Firebase 3 : creating a custom authentication token using . 网络和 c#

转载 作者:可可西里 更新时间:2023-11-01 08:06:30 27 4
gpt4 key购买 nike

我正在尝试使用自定义 token 实现 Firebase 3 身份验证机制(如 https://firebase.google.com/docs/auth/server/create-custom-tokens 中所述)。

我的服务器是 ASP.NET MVC 应用程序。

因此,根据说明 (https://firebase.google.com/docs/server/setup),我为我的 Firebase 应用程序创建了一个服务帐户,并生成了一个“.p12”格式的 key 。

之后,根据此处的说明 (https://firebase.google.com/docs/auth/server/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library),我尝试生成一个自定义 token 并使用在上一步中收到的 key 对其进行签名。对于 token 生成,我使用了 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 得到一个错误说:

Error authenticating Firebase user. Code: auth/invalid-custom-token Message: The custom token format is incorrect. Please check the documentation.

尝试添加不同的 token 过期控制声明也无济于事。

我还尝试使用“dvsekhvalnov/jose-jwt”库生成 token ,但无法使用“RS256”算法。

所以问题:

对我做错了什么有什么建议吗?

最佳答案

这个纯 .NET 解决方案适用于我,使用 Org.BouncyCaSTLe (https://www.nuget.org/packages/BouncyCastle/) 和 Jose.JWT (https://www.nuget.org/packages/jose-jwt/) 库。

我遵循了这些步骤:

  • 在 Firebase 控制台中,点击左上角项目名称旁边的“齿轮”图标,然后点击“权限”。
  • 在 IAM 和管理页面,点击左侧的“服务帐户”
  • 点击顶部的“创建服务帐户”,输入“服务帐户名称”,在角色选择中选择“项目->编辑”,勾选“提供新私钥”复选框并选择 JSON
  • 点击“创建”并下载服务帐户 JSON 文件并妥善保管。
  • 在合适的文本编辑器中打开服务帐户 JSON 文件并将值放入以下代码中:

    // private_key from the Service Account JSON file
    public static string firebasePrivateKey=@"-----BEGIN PRIVATE KEY-----\nMIIE...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n-----END PRIVATE KEY-----\n";

    // Same for everyone
    public static string firebasePayloadAUD="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";

    // client_email from the Service Account JSON file
    public static string firebasePayloadISS="serviceaccountname@projectname.iam.gserviceaccount.com";
    public static string firebasePayloadSUB="serviceaccountname@projectname.iam.gserviceaccount.com";

    // the token 'exp' - max 3600 seconds - see https://firebase.google.com/docs/auth/server/create-custom-tokens
    public static int firebaseTokenExpirySecs=3600;

    private static RsaPrivateCrtKeyParameters _rsaParams;
    private static object _rsaParamsLocker=new object();

    void Main() {
    // Example with custom claims
    var uid="myuserid";
    var claims=new Dictionary<string, object> {
    {"premium_account", true}
    };
    Console.WriteLine(EncodeToken(uid, claims));
    }

    public static string EncodeToken(string uid, Dictionary<string, object> claims) {
    // Get the RsaPrivateCrtKeyParameters if we haven't already determined them
    if (_rsaParams == null) {
    lock (_rsaParamsLocker) {
    if (_rsaParams == null) {
    StreamReader sr = new StreamReader(GenerateStreamFromString(firebasePrivateKey.Replace(@"\n","\n")));
    var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
    _rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
    }
    }
    }

    var payload = new Dictionary<string, object> {
    {"claims", claims}
    ,{"uid", uid}
    ,{"iat", secondsSinceEpoch(DateTime.UtcNow)}
    ,{"exp", secondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs))}
    ,{"aud", firebasePayloadAUD}
    ,{"iss", firebasePayloadISS}
    ,{"sub", firebasePayloadSUB}
    };

    return Jose.JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256);
    }

    private static long secondsSinceEpoch(DateTime dt) {
    TimeSpan t = dt - new DateTime(1970, 1, 1);
    return (long)t.TotalSeconds;
    }

    private static Stream GenerateStreamFromString(string s) {
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
    }

为了使它在 IIS 中正常工作,我需要更改应用程序的池标识并将“加载用户配置文件”设置设置为 true。

关于c# - Firebase 3 : creating a custom authentication token using . 网络和 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188122/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com