Azure  

๐Ÿ”ฅ Send Push Notifications via Google Firebase v1 API using .NET Core

Push notifications are a critical part of modern apps โ€” they keep users informed and engaged in real-time.
In this article, weโ€™ll learn how to send push notifications from a .NET Core Web API using the Firebase Cloud Messaging (FCM) v1 API โ€” the latest and most secure way to communicate with client apps.

๐Ÿง  What is Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you send notifications and data messages reliably to Android, iOS, and web clients.

With the v1 HTTP API, Google moved from legacy key-based authentication to OAuth2-based authentication using service accounts, providing better security and scalability.

๐Ÿ‘‰ Official Documentation:
Firebase Cloud Messaging HTTP v1 API (Google)

๐ŸŽฏ Why Use the v1 API?

FeatureLegacy APIv1 API
AuthenticationServer KeyOAuth2 (Service Account)
Message FormatJSON (limited)Structured JSON (with advanced options)
TargetingTokens / TopicsTokens / Topics / Conditions
Platform SupportBasicFull (Android, iOS, Web)
Future SupportDeprecatedโœ… Active

๐Ÿงฑ Step-by-Step Implementation in .NET Core

Letโ€™s implement a .NET Core Web API that can send notifications using Firebase Cloud Messaging v1 API.

โš™๏ธ Step 1. Create a .NET Core Web API Project

dotnet new webapi -n FirebasePushAPI
cd FirebasePushAPI

๐Ÿ“ฆ Step 2. Install Required NuGet Packages

Install packages for Google Auth and HTTP communication:

dotnet add package Google.Apis.Auth
dotnet add package Newtonsoft.Json

๐Ÿ”‘ Step 3. Create a Firebase Service Account Key

  1. Go to Firebase Console.

  2. Navigate to Project Settings โ†’ Service Accounts โ†’ Generate new private key.

  3. Download the JSON file and save it securely (e.g., /App_Data/firebase-key.json).

โš ๏ธ Never commit this file to source control.

๐Ÿงฉ Step 4. Create a Model for Notification Request

namespace FirebasePushAPI.Models
{
    public class FcmNotificationRequest
    {
        public string Token { get; set; }  // FCM device token
        public string Title { get; set; }
        public string Body { get; set; }
        public string ImageUrl { get; set; }
    }
}

๐Ÿช„ Step 5. Create a Firebase Notification Service

Create a new file Services/FirebaseService.cs:

using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace FirebasePushAPI.Services
{
    public class FirebaseService
    {
        private readonly string _projectId = "your-firebase-project-id";
        private readonly string _firebaseKeyPath = "App_Data/firebase-key.json";

        public async Task<bool> SendNotificationAsync(string token, string title, string body, string imageUrl = null)
        {
            var message = new
            {
                message = new
                {
                    token = token,
                    notification = new
                    {
                        title = title,
                        body = body,
                        image = imageUrl
                    }
                }
            };

            var accessToken = await GetAccessTokenAsync();

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", accessToken);

                var json = JsonConvert.SerializeObject(message);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync(
                    $"https://fcm.googleapis.com/v1/projects/{_projectId}/messages:send",
                    content);

                return response.IsSuccessStatusCode;
            }
        }

        private async Task<string> GetAccessTokenAsync()
        {
            GoogleCredential credential;

            using (var stream = new FileStream(_firebaseKeyPath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                    .CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
            }

            var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
            return token;
        }
    }
}

๐Ÿง  Explanation

  • Generates an OAuth2 access token using the service account JSON.

  • Sends a POST request to https://fcm.googleapis.com/v1/projects/{project_id}/messages:send.

  • The token, title, and body are passed dynamically.

๐Ÿงฎ Step 6. Create an API Controller

Create Controllers/NotificationController.cs:

using Microsoft.AspNetCore.Mvc;
using FirebasePushAPI.Models;
using FirebasePushAPI.Services;

namespace FirebasePushAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class NotificationController : ControllerBase
    {
        private readonly FirebaseService _firebaseService;

        public NotificationController()
        {
            _firebaseService = new FirebaseService();
        }

        [HttpPost("send")]
        public async Task<IActionResult> SendNotification([FromBody] FcmNotificationRequest request)
        {
            var result = await _firebaseService.SendNotificationAsync(request.Token, request.Title, request.Body, request.ImageUrl);

            if (result)
                return Ok(new { success = true, message = "Notification sent successfully" });
            else
                return BadRequest(new { success = false, message = "Failed to send notification" });
        }
    }
}

๐Ÿงช Step 7. Test API in Postman

POST URL

https://localhost:5001/api/notification/send

Request Body (JSON)

{"token": "DEVICE_FCM_TOKEN","title": "Welcome!","body": "Your registration was successful ๐ŸŽ‰","imageUrl": "https://yourdomain.com/welcome.png"}

Response

{"success": true,"message": "Notification sent successfully"}

โœ… The notification should instantly appear on your mobile device or web app registered with Firebase.

โšก Bonus: Sending to a Topic Instead of a Single Token

If you want to send to a topic (e.g., โ€œnewsโ€):

Replace this block:

token = token,

with:

topic = "news",

Then, your Firebase clients should subscribe to the topic using the FCM SDK.

๐Ÿ“š Subscribe to FCM Topics (Docs)

๐Ÿงฉ Common Errors & Fixes

ErrorCauseSolution
401 UnauthorizedInvalid service account or scopeEnsure correct JSON key and project ID
404 Not FoundWrong endpointCheck FCM v1 API URL
InvalidRegistrationInvalid device tokenEnsure valid token from FCM SDK
Permission deniedMissing Firebase Messaging permissionCheck IAM roles in GCP Console

๐Ÿ”— External References

  • Firebase Cloud Messaging v1 API Docs

  • Google OAuth2 Authentication for Service Accounts

  • Firebase Admin SDK Setup Guide

  • Send Messages with FCM REST API

๐Ÿ Conclusion

By integrating Firebase v1 API with your .NET Core Web API, you can deliver real-time push notifications to any platform โ€” securely and efficiently.

This modern approach replaces the old FCM server key method with OAuth2 tokens, offering better security and control for enterprise-grade applications.

Whether itโ€™s order updates, chat alerts, or system notifications, Firebase + .NET Core makes it fast and reliable.