Firebase身份验证asp.net核心

本文关键字:核心 net asp 身份验证 Firebase | 更新日期: 2023-09-27 18:04:28

成功登录Firebase后,我们收到了一个JWT令牌。

为了添加授权到我的asp.net应用程序,我试图添加一个JwtBearerAuthentication到我的中间件。

我已经尝试了以下JwtBearerOptions:

 var options = new JwtBearerOptions
        {
            Audience = "myApp",
            Authority = "https://securetoken.google.com"
        };

 var options = new JwtBearerOptions
        {
            Audience = "myApp",
            Authority = "https://securetoken.google.com/myApp"
        };

不幸的是,这不起作用。我的权限URL可能不正确。

有人知道哪个权限URL是正确的吗?

Firebase身份验证asp.net核心

JWT验证需要手动执行:source

下面的代码正在验证FirebaseToken (JWT):

    //Download certificates from google
    HttpClient client = new HttpClient();
    var jsonResult = client.GetStringAsync("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com").Result;
    //Convert JSON Result
    var x509Metadata = JObject.Parse(jsonResult)
                        .Children()
                        .Cast<JProperty>()
                        .Select(i => new x509Metadata(i.Path, i.Value.ToString()));
    //Extract IssuerSigningKeys
    var issuerSigningKeys = x509Metadata.Select(s => s.X509SecurityKey);
    //Setup JwtTokenHandler 
    var handler = new JwtSecurityTokenHandler();
    SecurityToken token;
    handler.ValidateToken(user.FirebaseToken, new TokenValidationParameters
    {
        IssuerSigningKeys = issuerSigningKeys,
        ValidAudience = "myApp",
        ValidIssuer = "https://securetoken.google.com/myApp",
        IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => issuerSigningKeys
    }, out token);
public class x509Metadata
{
    public string KID { get; set; }
    public string Certificate { get; set; }
    public X509SecurityKey X509SecurityKey { get; set; }
    public x509Metadata(string kid, string certificate)
    {
        KID = kid;
        Certificate = certificate;
        X509SecurityKey = BuildSecurityKey(Certificate);
    }
    private X509SecurityKey BuildSecurityKey(string certificate)
    {
        //Remove : -----BEGIN CERTIFICATE----- & -----END CERTIFICATE-----
        var lines = certificate.Split(''n');
        var selectedLines = lines.Skip(1).Take(lines.Length - 3);
        var key = string.Join(Environment.NewLine, selectedLines);
        return new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(key)));
    }
}

Firebase在这里发布标准格式的JWKs:

https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com

(尽管他们在文档中没有提到)

我在这里找到了这个信息:https://github.com/cfworker/cfworker/issues/89#issuecomment-748422827