Coder Social home page Coder Social logo

firebase / firebase-admin-dotnet Goto Github PK

View Code? Open in Web Editor NEW
366.0 59.0 131.0 1.28 MB

Firebase Admin .NET SDK

Home Page: https://firebase.google.com/docs/admin/setup

License: Apache License 2.0

C# 99.61% Shell 0.35% PowerShell 0.04%
firebase firebase-auth firebase-admin-sdk firebase-admin c-sharp dotnet

firebase-admin-dotnet's Introduction

Build Status

Firebase Admin .NET SDK

Table of Contents

Overview

Firebase provides the tools and infrastructure you need to develop apps, grow your user base, and earn money. The Firebase Admin .NET SDK enables access to Firebase services from privileged environments (such as servers or cloud) in .NET. Currently this SDK provides Firebase custom authentication support.

For more information, please visit the Firebase Admin SDK setup guide.

Installation

The Firebase Admin .NET SDK is available on Nuget as FirebaseAdmin. Use the following command to install it with the Nuget package manager:

$ Install-Package FirebaseAdmin -Version $VERSION

Or use the dotnet command-line utility as follows:

$ dotnet add package FirebaseAdmin --version $VERSION

Contributing

Development of the Admin .NET SDK is mostly driven by our open source community. We welcome and encourage contributions from the developer community to further improve and expand this project. If you would like a new feature or an API added to this SDK, please file an issue and provide a pull request. You can use other Firebase Admin SDKs as a reference on how certain features should be implemented:

Please refer to the CONTRIBUTING page for more information about how you can contribute to this project. In addition to the pull requests, We also welcome bug reports, feature requests, and code review feedback.

Supported Frameworks

Admin .NET SDK supports the following frameworks:

  • .NET Framework 4.6.2+
  • .NET Standard 2.0
  • .NET 6.0+

This is consistent with the frameworks supported by other .NET libraries associated with Google Cloud Platform.

Documentation

License and Terms

Firebase Admin .NET SDK is licensed under the Apache License, version 2.0.

Your use of Firebase is governed by the Terms of Service for Firebase Services.

firebase-admin-dotnet's People

Contributors

bojeil-google avatar christopherlenz avatar cmpcdaly avatar densmoke avatar dependabot[bot] avatar doris-ge avatar egilmorez avatar hiranya911 avatar jonathanedey avatar kcieslinski avatar kentcb avatar kentengjin avatar lahirumaramba avatar levimatheri avatar mathbunny avatar nicotinez avatar nixj14 avatar odonno avatar pwujczyk avatar rannyranny avatar renatoc8 avatar rsgowman avatar samtstern avatar scruffyprodigy avatar vikrum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-admin-dotnet's Issues

Custom data on FirebaseAdmin.Messaging.Notification?

Hello,
I'm trying to send a notification with this sdk and I'm supposed to set "click_action":"FCM_PLUGIN_ACTIVITY" on the notification object so that our cordova app can handle click events. Is there any way to do this via the sdk?

FCM: support for multiple recipients/batching

I need to send notifications to multiple users. I was surprised to find that this SDK does not support multiple recipients/batching, even though the Java and Node SDKs do. See here, for example.

Why is this? And what is the recommendation for those, like me, who need to send notifications to many users? I am currently getting by with the legacy API, but had hoped to switch to the new. I expected the SDK would make things simple, but now it seems I can't even use it.

Delete Users

It would be rad if you could support deleting users! :)

CreateCustomTokenAsync throws Exception: "Method Not Found System.String.TrimEnd"

@hiranya911

The unit tests succeed when calling JwtUtils::UrlSafeBase64Encode around line 89 with this code:
return base64Value.TrimEnd('=').Replace('+', '-').Replace('/', '_');

I don't understand how that is so, since System.String.TrimEnd takes as a parameter a char array and you are passing a single char: '='

After recompiling the project with this change to "TrimEnd", it now works as expected in my project:
return base64Value.TrimEnd(new[] { '=' }).Replace('+', '-').Replace('/', '_');

Without my fix, here is the stack trace I get when calling CreateCustomTokenAsync:

Method not found: 'System.String System.String.TrimEnd(Char)'. at FirebaseAdmin.Auth.JwtUtils.UrlSafeBase64Encode(Byte[] bytes)   at FirebaseAdmin.Auth.JwtUtils.Encode(Object obj)   at FirebaseAdmin.Auth.JwtUtils.<CreateSignedJwtAsync>d__3.MoveNext()--- End of stack trace from previous location where exception was thrown ---   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)   at FirebaseAdmin.Auth.FirebaseTokenFactory.<CreateCustomTokenAsync>d__8.MoveNext()--- End of stack trace from previous location where exception was thrown ---   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)   at FirebaseAdmin.Auth.FirebaseAuth.<CreateCustomTokenAsync>d__13.MoveNext()--- End of stack trace from previous location where exception was thrown ---   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)   at FirebaseAdmin.Auth.FirebaseAuth.<CreateCustomTokenAsync>d__11.MoveNext()--- End of stack trace from previous location where exception was thrown ---   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)   at FirebaseAdmin.Auth.FirebaseAuth.<CreateCustomTokenAsync>d__10.MoveNext()--- End of stack trace from previous location where exception was thrown ---   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()   at UserQuery.d__11.MoveNext() in C:\Users\mikep\AppData\Local\Temp\LINQPad5_jkekndcd\query_ghgvxj.cs:line 151
--`

Request all users

This SDK shall also implement a functionality to retrieve all users. This is already implemented in the other 3 languages and is a main function for an admin SDK.

Issue with connecting to Firebase

Hi, I have created a .Net API that sends a notification to users.
It was working fine till yesterday, and Now I am getting below error:
FirebaseMessagingException - Timed out while making an API call: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

I suspect, there is something wrong with the network connectivity. But while trying to send notification via Postman on "https://fcm.googleapis.com/fcm/send", The connection is successful.

Is there a list of URLs that I can whitelist to solve this problem?
Any help would be greatly appreciated.
Thanks in advance.

custom claims are not writeable via update or create

The Create- and Update-Methods use the UserRecordArgs-class. But the CustomClaims-property is only internal. I assume this property should be public, otherwise the test UpdateUserSetCustomClaims in FirebaseUserManagerTest makes no sense.

        [Fact]
        public async Task UpdateUserSetCustomClaims()
        {
            var handler = new MockMessageHandler() { Response = CreateUserResponse };
            var userManager = this.CreateFirebaseUserManager(handler);
            var customClaims = new Dictionary<string, object>()
            {
                    { "admin", true },
                    { "level", 4 },
                    { "package", "gold" },
            };

            await userManager.UpdateUserAsync(new UserRecordArgs()
            {
                Uid = "user1",
                CustomClaims = customClaims,
            });

            var request = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>(handler.LastRequestBody);
            Assert.Equal(2, request.Count);
            Assert.Equal("user1", request["localId"]);
            var claims = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>((string)request["customAttributes"]);
            Assert.True((bool)claims["admin"]);
            Assert.Equal(4L, claims["level"]);
            Assert.Equal("gold", claims["package"]);
        }

How can I get ID Token from custom token?

How can I get ID Token from custom token?

[Fact]
public void Get_ID_Token_For_Service_Account_Test()
{
    using (Stream stream = new FileStream(ServiceAccountJsonKeyFilePath, FileMode.Open, FileAccess.Read))
    {
        ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
        FirebaseApp.Create(new AppOptions
        {
            Credential = GoogleCredential.FromServiceAccountCredential(credential),
            ServiceAccountId = ServiceAccountId,
        });
        var uid = "Some UID";
        var additionalClaims = new Dictionary<string, object>
        {
            {"dmitry", "pavlov"}
        };
        string customToken = FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, additionalClaims).Result;

        string idToken = null; // How to get this? 

        FirebaseToken token = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken, CancellationToken.None).Result;

        Assert.NotNull(token);
        Assert.True(token.Claims.ContainsKey("dmitry"));
    }
}

I see samples for some other languages/platforms but not for C# - how to get ID token via current user here - Retrieve ID tokens on clients. But for C# neither UserRecord nor FirebaseAuth provides ID Token. Any pointers are much appreciated.

Is there any documentation on how to unit test Firebase SDK?

I'm trying to write MS Unit tests with Moq framework to test my auth logic with Firebase implementation.

I've tried googling Firebase .Net Unit testing but haven't found anything relevant.

The Firebase SDK has no Interfaces and all the classes are sealed so its not possible to mock it using Moq.

Aside from wrapping all the methods in their own custom methods (which i successfully did with VerifyIdTokenAsync) as this would be a lot more work than its worth.

Heads up notification not displaying in Android 7.1

I am trying to send a heads up notification to a specific topic on a variety of devices.
I do have devices on Android 7.1 and +.

Everything is ok when I try to send a notification to Android 7.2+.
Notification channels are used and I created a channel with an appropriate importance so the heads up notification is showing properly.

On this link we can see :

Example conditions that might trigger heads-up notifications include the following:

  • The user's activity is in fullscreen mode (the app uses fullScreenIntent).
  • The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.
  • The notification channel has high importance on devices running Android 8.0 (API level 26) and higher.

So a heads up notification on Android 7.1 seems to require high priority and a ringtone or vibration.

I need to have a single code to send notifications to Android 7.1 and Android 7.1+ so here is the code I wrote :

var message = new FirebaseAdmin.Messaging.Message()
{
    Topic = "my-topic",
    Webpush = new WebpushConfig()
    {
        Notification = new WebpushNotification()
        {
            Renotify = true,
            RequireInteraction = true,
            Silent = false,
            Vibrate = new int[] { 500, 500, 500, 500, 500 },
        }
    },
    Android = new AndroidConfig()
    {
        TimeToLive = new TimeSpan(0, 30, 0),
        Priority = Priority.High,
        Notification = new AndroidNotification()
        {
            Tag = "my-tag",
            Title = "my title",
            Body = "my body",
            ChannelId = "my-channel",
            Sound = "default"
        }
    }
};

// Send a message to the devices subscribed to the provided topic.
await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(false);

I send a Sound as "default" in the Android config and a high priority.
When my app is not opened, I receive the notification but it stays in the tray and does not show up as heads-up.
Why isn't the notification showing up as heads-up ? Is the "default" value for Sound supported ?

click_action for WebpushNotification

How to use click_action with WebpushNotification for web?

Like this?

            var message = new MulticastMessage
            {
                Webpush = new WebpushConfig()
                {
                    Notification = new WebpushNotification()
                    {
                        Title = title,
                        Body = body,
                        Icon = icon
                    },
                    FcmOptions = new WebpushFcmOptions
                    {
                        Link = clickAction
                    }
                },
                Tokens = registrationTokens
            };

Control Access With Custom Claims

We have an ASP.NET Core MVC backend with self hosted Identity Authentication with a custom provider. It is not fully tested and by self hosting it not so secure, so we would like to use an authentication service and Firebase Authentication is the most promising.

BUT the dotnet admin sdk does not have the "Control Access With Custom Claims" feature while role management in our app is core thing. So without this feature we cannot use Firebase Authentication.

Do you have any ETA when it will be added? It is our most urgent feature request.

I saw that you are asking the community to contribute, we really would like to but we are an early stage startup so we do not have the resources to help right now. But if we can successfully integrate Firebase Authentication with our webapp we will contribute in the future definitely!

Is this too complicated

I landed here because I needed to verify a Firebase ID token, but was surprised that this is so involved (multiple packages to download, creating a FirebaseApp is quite involved). After all, only the FB Project ID is needed to get the full profile through Firebase's own API. So a "cheap" validation could be done by just sending the token with a single HTTP POST to

https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=PROJECT_KEY

Anyhow, I ended up writing a validator that just uses .NET's built-in capabilities along with the OpenId specs, which also just requires the project ID. This looks lean enough, but leaves me wondering whether I overlooked anything. If not: Would it be feasible to simplify the setup of the Auth stack?

public class FirebaseTokenValidator
{
    private ConfigurationManager<OpenIdConnectConfiguration> configurationManager;

    public string Issuer { get; }
    public string ProjectId { get; set; }

    public FirebaseTokenValidator(string firebaseProjectId)
    {
        ProjectId = firebaseProjectId;
        Issuer = "https://securetoken.google.com/" + firebaseProjectId;
        var metadataAddress = $"{Issuer}/.well-known/openid-configuration";
        var retriever = new OpenIdConnectConfigurationRetriever();
        configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataAddress, retriever);
    }

    
    public async Task<ClaimsPrincipal> ValidateToken(string token)
    {
        OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);

        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = Issuer,
            ValidateIssuerSigningKey = true,
            IssuerSigningKeys = openIdConfig.SigningKeys,
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidAudiences = new[] { ProjectId }
        };

        //create token validator (not 100% sure it's thread safe, so better be safe than sorry)
        var tokenHandler = new JwtSecurityTokenHandler();
        ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out var rawValidatedToken);
        
        //to get the token instead:
        //return (JwtSecurityToken)rawValidatedToken;

        return principal;
    }
}

Firebase 404 NOT_FOUND

I am trying to implement firebase admin into ASP.NET core but I am missing something...
Everytime I run my code I get the following error:

Response status code does not indicate success: 404 (NotFound)
{
  "error": {
    "code": 404,
    "message": "Requested entity was not found.",
    "errors": [
      {
        "message": "Requested entity was not found.",
        "domain": "global",
        "reason": "notFound"
      }
    ],
    "status": "NOT_FOUND"
  }
}

The code that I am running:

var message = new Message
{
    Token = fcmToken,
    Data = new Dictionary<string, string>
    {
        {"title", notification.Title},
        {"body", notification.Message},
        {"channel", notification.Channel},
        {"level", ((int)notification.Level).ToString()},
        {"link", notification.Link}
    }
};

try
{
    var fcmResult = await FirebaseMessaging.DefaultInstance.SendAsync(message);
}
catch (Exception ex)
{

}

Registration:

if (FirebaseApp.DefaultInstance == null)
{
    FirebaseApp.Create(new AppOptions
    {
        Credential = GoogleCredential.FromJson(Settings.Default.Firebase_Server_Auth)
    });
}

Github link: https://github.com/kevingoos/FirebaseAdminTest
Stackoverflow: https://stackoverflow.com/questions/56499904/firebaseadmin-messaging-returning-404-not-found

Runtime compilation error (Razor View)

Not sure if this is a real issue, or just a (package dependency) compatibility problem.

I encountered the following runtime compilation error (Razor View) after adding FirebaseAdmin to my ASP .NET MVC 5 project:

It was actually caused by the "System.Collections.Immutable" package that triggered warning CS1685 (type defined in multiple assemblies).

I forked the repository and removed the "System.Collections.Immutable" dependency, which solved my issue:

Decided to open this issue to let you know. Thanks!

How to generate a token?

https://firebase.google.com/docs/admin/setup
I follow this above page to generate new private key and store key file,
and then set the GOOGLE_APPLICATION_CREDENTIALS environment variable successfully.
I just only get two file from firebase ,one is "google-services.json" and the other is 'fir-database-fbbf0-firebase-adminsdk-cboyj-a31168588e.json'(private key file)

I want to send message via firebase to client App device,but It always shows the error message "The registration token is not a valid FCM registration token".
I don,t know the parameter of "CreateCustomTokenAsync" Function should fill what ???
I have ever filled my gmail or account name ,but both are invalid.

      public static async Task SendToTopicAsync()
       {
           try
           {
                   var defaultApp = FirebaseApp.Create(new AppOptions()
                   {
                       Credential = GoogleCredential.GetApplicationDefault(),
                   });

                   var uid = "[email protected]";
                   string customToken = await 
                   FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid);
  
                   var message = new FirebaseAdmin.Messaging.Message()
                   {
                       Data = new Dictionary<string, string>()
                   {
                       { "score", "850" },
                       { "time", "2:45" },
                   },
                       Token = customToken,
                   };

                   string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
                   Console.WriteLine("Successfully sent message: " + response);

           }
           catch (System.Exception e)
           {
               System.Diagnostics.Debug.WriteLine("Error: " + e);
               throw;
           }

       }
              
       private void Button1_Click(object sender, EventArgs e)
       {
           Task.Run(async () => await SendToTopicAsync());            
      }

The caller does not have permission [403] with firebase cloud messaging.

Hi,

I'm using ASP.Net Core as my back-end for my project.
In my project. I need to send push notifications to my clients.

I registered FirebaseApp and FirebaseMessaging as dependency injection components.

Here is my code:

/// <summary>
        /// Setup firebase application.
        /// </summary>
        protected static void SetupCloudApplication(IServiceCollection services, IConfiguration configuration)
        {
            // Setup firebase app.
            services.AddSingleton(x =>
            {
                var options = new AppOptions();
                var cloudMessagingSettings = x.GetService<IOptions<FirebaseCloudMessagingSettingModel>>().Value;
                if (cloudMessagingSettings == null)
                    throw new Exception("No cloud message settings have been found");

                // Find hosting environment.
                var hostingEnvironment = x.GetService<IHostingEnvironment>();

                // Find credential settings file.
                var credentialFile = Path.Combine(hostingEnvironment.ContentRootPath,
                    cloudMessagingSettings.CredentialFile);

                options.Credential = GoogleCredential.FromFile(credentialFile)
                    .CreateScoped("https://www.googleapis.com/auth/firebase.messaging", "https://www.googleapis.com/auth/cloud-platform");

                options.ProjectId = cloudMessagingSettings.ProjectId;
                options.ServiceAccountId = cloudMessagingSettings.ServiceAccountId;
                return FirebaseApp.Create(options);
            });

            // Setup cloud messaging.
            services.AddScoped(x =>
            {
                var cloudApp = x.GetService<FirebaseApp>();
                return FirebaseMessaging.GetMessaging(cloudApp);
            });
        }

Following this tutorial, I can get a service account json file. I downloaded that file and saved into my web project.

DI components were OK, my application started successfully.
When I tried sending a push message to my clients. I received an error:

2019-05-25 16:13:13.546 +08:00 [Error] Google.Apis.Requests.RequestError
The caller does not have permission [403]
Errors [
Message[The caller does not have permission] Location[ - ] Reason[forbidden] Domain[global]
]

What was wrong with my code ?

Thanks

System.ArgumentException: "The default FirebaseApp already exists."

Hi!

Once I try to initialize a new instance of FirebaseApp in another WPF window a get following message: System.ArgumentException: "The default FirebaseApp already exists."

This message also appears within Android, React etc. and there are solutions for it, but I can't find any solution for .net C#?
So how to avoid this error?

Implement Cloud Messaging Feature

We are in the process of adding Firebase into an existing project in order to add a real-time chat (using Firestore), and we would like to switch to FCM for push notifications. This would simplify sending chat-related notifications directly through Firebase, but we still need to send other notifications from the .NET backend, and thus need the Cloud Messaging feature.

I couldn't find a roadmap for the .NET Admin SDK so I'm just putting this out here as our most urgent feature request.

customAttributes size limitation is calculated with UTF-16, but it is UTF-8

If the byte-count is calculated with Unicode (UTF-16), it needs 2 bytes per character. The Java and Golang SDK use UTF-8 for that. This way these SDK's are able to store 1000 characters, whereas the dotnet SDK can only store 500 characters.

Can be found in CheckCustomClaims-method of UserRecord-class.

var customClaimsString = SerializeClaims(customClaims); var byteCount = Encoding.Unicode.GetByteCount(customClaimsString); if (byteCount > 1000) { throw new ArgumentException($"Claims have to be not greater than 1000 bytes when serialized"); }

Error message on APS notifications

Hello - When I'm sending APS notifications, I'm getting an error as follows:

{
  "error": {
    "code": 400,
    "message": "Value of [aps] must be a non-empty dictionary.",
    "errors": [
      {
        "message": "Value of [aps] must be a non-empty dictionary.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

I am sending a message that does have [aps] populated. Is there something else I could be missing?

           var fcmMessage = new Message()
            {
                Token = address,
                Apns = new ApnsConfig()
                {
                    Aps = new Aps()
                    {
                        ContentAvailable = contentAvailable,
                        Badge = badge,
                        Sound = sound,
                    },
                },
            };

            if (data != null && data.Count > 0)
            {
                fcmMessage.Apns.CustomData = data;
            }

            if (!silentOnApns)
            {
                fcmMessage.Notification = new Notification()
                {
                    Title = title,
                    Body = message,
                };
            }

            var firebaseMessaging = FirebaseMessaging.GetMessaging(this.firebaseApp);

            return await firebaseMessaging.SendAsync(fcmMessage);```

Thanks!

Firebase ID token issued at future timestamp Error

Version: 1.2.0

I am trying to verify the firebase token but sometimes, it is throwing Firebase ID token issued at future timestamp error.

                var firebaseAppInstance = FirebaseApp.GetInstance(firebaseAppName);

                if (firebaseAppInstance == null)
                {
                    firebaseAppInstance = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = GoogleCredential.FromFile("firebase-servicekey.json")
                    }, firebaseAppName);
                }

                var decodedToken = await FirebaseAuth.GetAuth(firebaseAppInstance).VerifyIdTokenAsync(firebaseToken);

Can you please see what's wrong here? Is there any consideration of clockSkew in this version of SDK?

Mute push notification׳s sound is not documented

I’m trying to use this library and I tried to find how to mute the sound of the push notification at all. I saw in the APS We have option to define sound as string but in the API I saw sound true/false. Is this missing in this lib. I didn’t find these in the documentations.

Support logging request & response while sending push message to server

Hi team,

I am using FirebaseAdmin for my project.
Currently, I don't see any any callback or delegate to help me to get the information of the requests | responses that are sent | recevied to | from firebase cloud messaging service.

I notice there is one property in AppOption named HttpClientFactory.
I wonder there are any examples about that to log the request | response or not. For now, I don't know how to implement logging without affecting to the library settings.

Thanks

Could you please provide pure dll that could be used in unity PC platform?

I just want to write unity editor extension that could administering firebase system in the editor. Such as minting token to login as any ID for testing process

But unity cannot use nuget officially. So if there would be pure dll and dependency or unitypackage that could easily include in the project that would be great

Is it possible?

Getting "not valid registration token" after upgrade to Version 1.8.0

After upgrading from V 1.7.0 to 1.8.0 I get the following error:

The registration token is not a valid FCM registration token

on calling FirebaseMessaging.SendAsync(). When I downgrade to V 1.7.0 everything works fine again. Same happens if I download a fresh admin JSON.

Here is a part of my code:

            ...
            FirebaseApp firebaseApp = FirebaseApp.Create(
                new AppOptions
                {
                    Credential = GoogleCredential.FromJson(firebaseCredentialJson)
                },
                "MY_APP");

            FirebaseMessaging firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);

            string response = await firebaseMessaging.SendAsync(
                CreateMessage(deviceToken, sentMessageId, title, text));
            ...

Did I miss any breaking change?

FR: Support Cloud Storage

firebase-admin-dotnet does not support Cloud Storage yet.
I'd like to contribute for it.

The simple specifications are as follows:

  • Need new class to handle Cloud Storage. Its name is FirebaseAdmin.Cloud.FirebaseStorage as an example.
  • FirebaseStorage instance is managed in FirebaseApp class.
  • FirebaseStorage instance has Google.Cloud.Storage.V1.StorageClient instance.
  • FirebaseStorage instance will return the StorageClient instance associated with the Firebase app.
  • Now the Bucket class is returned in other Java/Python SDK. But the Bucket class in .NET is almost data class. It's not neccesary to be returned(It's my opinion).
  • When calling FirebaseApp.Delete(), StorageClient.Dispose() is called.

I would like to open a pull request about the above if there are no problems.

"UpdateUser"-method used by "SetCustomUserClaimsAsync" throws "MISSING_LOCAL_ID"

The serialized "UserRecord" JSON uses the property-names of the "UserRecord"-class. This is wrong and has to be remapped.

Currently:
{ "Uid":"40MgueENCLft6rl5Zs4Et0FuiQF3", "ProviderId":"firebase", "EmailVerified":false, "Disabled":false, "TokensValidAfterTimestamp":0, "customAttributes":"{\"Roles\":[\"AAA\",\"BBB\"]}" }

But correct properties would be:

  • localId
  • email
  • disableUser

Edit: ahh I see that you have prepared a pull-request with fixes for that.

FCM - Too dificult to work with the response error codes

The FirebaseException seems a bit oversimplified by just wrapping the HttpRequestException and also not aligned with https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode

Error code enums should be returned somewhere. What I have to at this point is to look up for status code (e.g. "[503]") in the FirebaseException.Message, which of course doesn't work in the case of UNSPECIFIED_ERROR from ErrorCode documentation.

For starters, maybe you could at least state what to look for at UNSPECIFIED_ERROR type of response. Propagating the error codes is important for exponential backoff implementations.

CollapseKey is set by default

Hello!

When I send a message client (Android app) receives it with CollapseKey.
The issue is when client returns online it receives only last message.

The code below sends message:

            var message = new Message
            {
                Data = new Dictionary<string, string>
                {
                    { AppConstants.Fcm.PAGE_ID, page.Id.ToString() },
                    { AppConstants.Fcm.IMAGE_URL, page.ImageUrl },
                    { AppConstants.Fcm.MEDIA_URL, page.MediaUrl },
                    { AppConstants.Fcm.TITLE, page.Title },
                    { AppConstants.Fcm.PAGE_URL, page.Url }
                },
                Topic = AppConstants.Fcm.NEWS_TOPIC
            };

            await FirebaseMessaging.DefaultInstance.SendAsync(message);

Call to load credentials with FirebaseAdmin does not work

Usually I post my issues on stack exchange, because I'm assuming the problem is mine. So I've done that...

But It occurs to me that on this one maybe I should log a bug. Sure seems to be one. So here's what I wrote...

I am working with FirebaseAdmin 1.9.1 and attempting to use the recommended method for this call:

FirebaseApp.Create(new AppOptions()  
{
  Credential = credential,
});

From all that I read, I can load the credential paramater via this...

var credential = await GoogleCredential.GetApplicationDefaultAsync();

or this

credential = GoogleCredential.FromFile("/your/path/to/glory/google-service-accounts.json");

And if the value of a special environment variable is set as so...

"GOOGLE_APPLICATION_CREDENTIALS": "/your/path/to/glory/google-service-accounts.json",

...the two approaches should produce the same, working, result.

Not so! Not so.

The 2nd version works, but the first, recommended, approach? Using GetApplicationDefaultAsync?

Not so much.

I have checked and re-checked, and the two strings containing "/your/path/to/glory/google-service-accounts.json" are identical, though obviously not the value I've pasted here.

GOOGLE_APPLICATION_CREDENTIALS I copied and pasted directly. And I can see it properly set in the environment variables.

In fact, just to add salt to my wounds, I tried this...

credential = GoogleCredential.FromFile(_configuration["GOOGLE_APPLICATION_CREDENTIALS"]);

And the credentials DID load.

Create custom token using a service account ID

Hi, I'm trying to create custom token for specified service account from different service account. I'm following this guide: https://firebase.google.com/docs/auth/admin/create-custom-tokens#using_a_service_account_json_file (Using a service account ID).
When I configure it like that and try to generate a token, that token is invalid. So I started debugging:

public static FirebaseTokenFactory Create(FirebaseApp app)
{
ISigner signer = null;
var serviceAccount = app.Options.Credential.ToServiceAccountCredential();
if (serviceAccount != null)
{
// If the app was initialized with a service account, use it to sign
// tokens locally.
signer = new ServiceAccountSigner(serviceAccount);
}
else if (string.IsNullOrEmpty(app.Options.ServiceAccountId))
{
// If no service account ID is specified, attempt to discover one and invoke the
// IAM service with it.
signer = new IAMSigner(app.Options.HttpClientFactory, app.Options.Credential);
}
else
{
// If a service account ID is specified, invoke the IAM service with it.
signer = new FixedAccountIAMSigner(
app.Options.HttpClientFactory, app.Options.Credential, app.Options.ServiceAccountId);
}

If I set debugger on here and set serviceAccount value to null, I get a valid token. So it seems like it's using wrong service account.

Can app.Options.Credential.ToServiceAccountCredential() be null? You cannot even initialize FirebaseApp without setting Credential = GoogleCredential.GetApplicationDefault().

Shouldn't the logic be that it should first check if a service account ID is specified and invoke the IAM service, and only if not it should go for other cases?

UpdateUser for all properties

At the moment there is only one update-function "SetCustomUserClaimsAsync". The internal called "UpdateUserAsync" from UserManager is capable to update all properties from the UserRecord.
It makes sense to delegate the generic "UpdateUserAsync"-method and make it usable in the "FirebaseAuth"-class.

Similar to the Java-SDK: https://github.com/firebase/firebase-admin-java/blob/55d403f20aabe4deb58e6b4dfc2592e6589f7339/src/main/java/com/google/firebase/auth/FirebaseAuth.java#L714-L741

Is FirebaseApp Instance Singleton?

I would like to know whether an Instance of FirebaseApp returned by FirebaseApp.Create() method Singleton?
If not, what is the cost of creating high number of instances of it? I am currently developing for Push Notifications using FCM. And any sample code available where the SDK is used with Service account authentication and FCM?

Reference code:

public void SendPushNotification()
        {
            var firebaseApp =
                FirebaseApp.Create(new AppOptions
                {
                    Credential = GoogleCredential.FromFile("path/to/service/account/file.json")
                });

            var firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);

            var message = new Message
            {
                Data = new Dictionary<string, string>
                {
                    { "Test", "Test" }
                },
                Token = ""
            };

            var response = firebaseMessaging.SendAsync(message);
        }

This will be called each time there's a new notification for each user.

Proposal: Implementation of InstanceIdClient (FCM topic management)

As per issue #83, I'm working on a conversion to C# from the Java InstanceIdClient to allow tokens to be added and removed from topics.

Guidelines said I should post here first, although I'm currently just working through unit & integration tests :)

Let me know if there's anything I should be aware of or bear in mind.

Firebase Console - Cloud Messaging Report

Hello,

we use this package to send push notifications to Android phones, which is working nicely.
But we can not see any send notification in the report (Firebase console -> Cloud Messaging Report).
Do you have an idea why?

Thanks

SendAllAsync - order of responses

This is more of a question and something that you might want to add to the documentation. When you send many messages in batch with SendAllAsync, is the order of the responses guaranteed to be in the same order as they had in the list provided to SendAllAsync? I need to handle notifications that couldn't be sent and would therefore need the response to be in the same order as the request so that I know what error repsonse that correlates to my local notificationId.

Looking at

private async Task<BatchResponse> SendBatchRequestAsync(
it seems like the responses are added to the response list in the order they arrive from BatchRequest, not honoring the index parameter.

Best way to determine specific errors?

I'm trying to determine when there is an invalid token, an expired token, message rate exceeded error, etc. (https://firebase.google.com/docs/cloud-messaging/send-message#admin_sdk_error_reference).

When i send a single message/notification to a token like so:
var response = await FirebaseMessaging.DefaultInstance.SendAsync(message);

I get the following response (I'm getting this when i catch a thrown exception from FirebaseMessaging... I think i must be using this incorrectly as this seems strange... shouldn't there be a response object?).

What am I doing that is incorrect? Shouldn't I be able to find a code that matches to whats in the admin_sdk_error_reference section? (link i have above)

Response status code does not indicate success: 400 (BadRequest)
{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "errors": [
      {
        "message": "The registration token is not a valid FCM registration token",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

Firebase admin proxy issue

Note: my firebase code is running on container behind the proxy and in my code i am configurating it like in image below .

image

Note: I used curl command to send notification using proxy and it works like a charm

but firebase admin code gives this error

{"EntryDate":"Fri Jun 28 09:34:42 +00:00 2019","Level":"ERROR","Message":{"body":"FirebaseAdmin.FirebaseException: Error while calling the FCM service. ---> System.Net.Http.HttpRequestException: No such device or address ---> System.Net.Sockets.SocketException: No such device or address\n at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)\n --- End of inner exception stack trace ---\n at Google.Apis.Http.ConfigurableMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)\n at Google.Apis.Auth.OAuth2.Requests.TokenRequestExtenstions.ExecuteAsync(TokenRequest request, HttpClient httpClient, String tokenServerUrl, CancellationToken taskCancellationToken, IClock clock)\n at Google.Apis.Auth.OAuth2.ServiceAccountCredential.RequestAccessTokenAsync(CancellationToken taskCancellationToken)\n at Google.Apis.Auth.OAuth2.TokenRefreshManager.RefreshTokenAsync()\n at Google.Apis.Auth.OAuth2.TokenRefreshManager.ResultWithUnwrappedExceptions[T](Task1 task)\n at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()\n at System.Threa

  | ding.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)\n--- End of stack trace from previous location where exception was thrown ---\n at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)\n--- End of stack trace from previous location where exception was thrown ---\n at Google.Apis.Auth.OAuth2.TokenRefreshManager.GetAccessTokenForRequestAsync(CancellationToken cancellationToken)\n at Google.Apis.Auth.OAuth2.ServiceAccountCredential.GetAccessTokenForRequestAsync(String authUri, CancellationToken cancellationToken)\n at Google.Apis.Auth.OAuth2.ServiceCredential.InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n at Google.Apis.Http.ConfigurableMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)\n at Google.Apis.Requests.BatchRequest.ExecuteAsync(CancellationToken cancellationToken)\n at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendBatchRequestAsync(IEnumerable1 messages, Boolean dryRun, CancellationToken cancellationToken)\n at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendAllAsync(IEnumerable1 messages, Boolean dryRun, CancellationToken cancellationToken)\n --- End of inner exception stack trace ---\n at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendAllAsync(IEnumerable1 messages, Boolean dryRun, CancellationToken cancellationToken)\n at FirebaseAdmin.Messaging.FirebaseMessaging.SendAllAsync(IEnumerable1 messages, Boolean dryRun, CancellationToken cancellationToken)\n at FirebaseAdmin.Messaging.FirebaseMessaging.SendAllAsync(IEnumerable1 messages, Boolean dryRun)\n at FirebaseAdmin.Messaging.FirebaseMessaging.SendAllAsync(IEnumerable1 messages)\n at PushNotificationsService.FirebaseHandler.FirebaseMessageComposer.SendMessageBatch(List1 messages) in /opt/app-root/src/Pu

Proxy Support

This API does not work when behind a corporate proxy. If you were to expose the HttpClientFactory creation in FirebaseMessaging.cs as a parameter it would allow proxies to be supported. If I get time, I'll create a pull-request illustrating the idea.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.