### Install Firebase Admin .NET SDK (.NET CLI) Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/README.md Use this command to install the Firebase Admin .NET SDK using the .NET command-line interface. ```bash $dotnet add package FirebaseAdmin --version $VERSION ``` -------------------------------- ### Install Firebase Admin .NET SDK (NuGet Package Manager) Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/README.md Use this command to install the Firebase Admin .NET SDK via the Nuget Package Manager console. ```powershell $Install-Package FirebaseAdmin -Version $VERSION ``` -------------------------------- ### Example Commit Message for Conventional Commits Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md This example demonstrates the required format for commit messages, including the type, scope, subject, and a detailed body with problem explanation, testing strategy, and context sources. ```text feat(fcm): Add support for multicast messages This change introduces a new `SendEachForMulticastAsync` method to the messaging client, allowing developers to send a single message to multiple tokens efficiently. Testing: Added unit tests with a mock server and an integration test in `FirebaseAdmin.IntegrationTests/MessagingTest.cs`. Context Sources Used: - id: firebase-admin-dotnet - id: firebase-admin-dotnet-messaging ``` -------------------------------- ### Run Integration Tests Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/CONTRIBUTING.md Execute integration tests for the Firebase Admin .NET SDK using the dotnet CLI. Ensure all necessary dependencies are installed. ```bash $ dotnet test FirebaseAdmin.IntegrationTests ``` -------------------------------- ### Conventional Commits Specification Example with Abbreviation Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md Shows an example of a commit title using an abbreviated scope for the Firebase Cloud Messaging (fcm) service, following the Conventional Commits specification. ```text feat(fcm): Add support for multicast messages ``` -------------------------------- ### Conventional Commits Specification Example Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md Illustrates the Conventional Commits format for commit titles, specifying the 'type', 'scope', and 'subject'. The scope should correspond to the service package changed. ```text fix(auth): Resolve issue with custom token verification ``` -------------------------------- ### Get OIDC Provider Configuration Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Retrieve an existing OIDC provider configuration by its unique ProviderId. This is useful for checking the current settings of a provider. ```csharp // Get OIDC provider OidcProviderConfig config = await FirebaseAuth.DefaultInstance .GetOidcProviderConfigAsync("oidc.myProvider"); Console.WriteLine($"{config.DisplayName}: {config.Enabled}"); ``` -------------------------------- ### Get SAML Provider Configuration Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Retrieve an existing SAML provider configuration by its ProviderId. This allows checking the current status and details of the SAML integration. ```csharp // Get SAML provider SamlProviderConfig config = await FirebaseAuth.DefaultInstance .GetSamlProviderConfigAsync("saml.myProvider"); Console.WriteLine($"{config.DisplayName}: {config.Enabled}"); ``` -------------------------------- ### Run Unit Tests with .NET CLI Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/CONTRIBUTING.md Execute the unit test suite using the `dotnet test` command. This is typically done during development. ```bash $ dotnet test FirebaseAdmin.Tests ``` -------------------------------- ### Create User Account with Full Details Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Use UserRecordArgs to specify all properties for a new user, including email, password, display name, and custom claims. Omit Uid to let Firebase generate it. ```csharp using FirebaseAdmin.Auth; // Create a user with full details UserRecordArgs args = new UserRecordArgs() { Uid = "custom-uid-12345", // Optional: let Firebase generate if omitted Email = "user@example.com", EmailVerified = false, PhoneNumber = "+11234567890", Password = "secretPassword123", DisplayName = "John Doe", PhotoUrl = "https://example.com/photos/johndoe.png", Disabled = false, }; try { UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args); Console.WriteLine($"Successfully created new user: {userRecord.Uid}"); Console.WriteLine($"Email: {userRecord.Email}"); Console.WriteLine($"Display Name: {userRecord.DisplayName}"); Console.WriteLine($"Provider ID: {userRecord.ProviderId}"); } catch (FirebaseAuthException ex) { Console.WriteLine($"Error creating user: {ex.Message}"); Console.WriteLine($"Auth error code: {ex.AuthErrorCode}"); } ``` -------------------------------- ### Run Unit Tests for .NET 4.6.2 Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md Execute unit tests specifically for the .NET 4.6.2 framework using the dotnet CLI. Ensure the correct path to the test project is provided. ```bash dotnet test FirebaseAdmin/FirebaseAdmin.Tests --framework net462 ``` -------------------------------- ### Configure SAML Provider Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Use SamlProviderConfigArgs to set up a new SAML provider. Key parameters include IdpEntityId, SsoUrl, and X509Certificates for identity provider verification. ```csharp using FirebaseAdmin.Auth; using FirebaseAdmin.Auth.Providers; // Create SAML provider var args = new SamlProviderConfigArgs() { DisplayName = "SAML Provider Name", Enabled = true, ProviderId = "saml.myProvider", IdpEntityId = "IDP_ENTITY_ID", SsoUrl = "https://example.com/saml/sso/1234/", X509Certificates = new List() { "-----BEGIN CERTIFICATE-----\nCERT1...\n-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\nCERT2...\n-----END CERTIFICATE-----", }, RpEntityId = "RP_ENTITY_ID", CallbackUrl = "https://project-id.firebaseapp.com/__/auth/handler", }; SamlProviderConfig saml = await FirebaseAuth.DefaultInstance .CreateProviderConfigAsync(args); Console.WriteLine($"Created SAML provider: {saml.ProviderId}"); ``` -------------------------------- ### Run Unit Tests for .NET 6.0 Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md Execute unit tests specifically for the .NET 6.0 framework using the dotnet CLI. Ensure the correct path to the test project is provided. ```bash dotnet test FirebaseAdmin/FirebaseAdmin.Tests --framework net6.0 ``` -------------------------------- ### Initialize Firebase App in .NET Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Initialize the FirebaseApp using Application Default Credentials or explicit service account keys. Supports creating multiple named app instances. ```csharp using FirebaseAdmin; using Google.Apis.Auth.OAuth2; // Initialize with Application Default Credentials (ADC) FirebaseApp.Create(); // Or initialize with explicit service account credentials FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json"), ProjectId = "your-project-id", ServiceAccountId = "your-service-account@project.iam.gserviceaccount.com" }); // Access the default instance FirebaseApp defaultApp = FirebaseApp.DefaultInstance; Console.WriteLine($"App name: {defaultApp.Name}"); // Create a named app instance for multiple projects FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("path/to/other-project-key.json"), }, "secondary-app"); // Get named instance and clean up when done FirebaseApp secondaryApp = FirebaseApp.GetInstance("secondary-app"); secondaryApp.Delete(); ``` -------------------------------- ### Configure OIDC Provider Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Use OidcProviderConfigArgs to set up a new OpenID Connect provider. Ensure the ProviderId is unique and matches your OIDC configuration. ```csharp using FirebaseAdmin.Auth; using FirebaseAdmin.Auth.Providers; // Create OIDC provider var createArgs = new OidcProviderConfigArgs() { DisplayName = "OIDC Provider Name", Enabled = true, ProviderId = "oidc.myProvider", ClientId = "CLIENT_ID", Issuer = "https://oidc.example.com", }; OidcProviderConfig oidc = await FirebaseAuth.DefaultInstance .CreateProviderConfigAsync(createArgs); Console.WriteLine($"Created OIDC provider: {oidc.ProviderId}"); ``` -------------------------------- ### Import Users with Password Hashes in C# Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Bulk import users from external systems, including their password hashes and salts. Supports various hashing algorithms like HMAC-SHA256. ```csharp using FirebaseAdmin.Auth; using FirebaseAdmin.Auth.Hash; using System.Text; // Import users with HMAC-SHA256 password hashing var users = new List() { new ImportUserRecordArgs() { Uid = "uid1", Email = "user1@example.com", PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"), PasswordSalt = Encoding.ASCII.GetBytes("salt1"), }, new ImportUserRecordArgs() { Uid = "uid2", Email = "user2@example.com", PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"), PasswordSalt = Encoding.ASCII.GetBytes("salt2"), }, }; var options = new UserImportOptions() { Hash = new HmacSha256() { Key = Encoding.ASCII.GetBytes("secretKey"), }, }; try { UserImportResult result = await FirebaseAuth.DefaultInstance .ImportUsersAsync(users, options); Console.WriteLine($"Successfully imported {result.SuccessCount} users"); Console.WriteLine($"Failed to import {result.FailureCount} users"); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user at index: {indexedError.Index}" + $ ``` -------------------------------- ### Clone and Restore Dependencies for Firebase Admin .NET SDK Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/CONTRIBUTING.md Clone the repository and restore dependencies to set up the local development environment for the Firebase Admin .NET SDK. ```bash git clone https://github.com/firebase/firebase-admin-dotnet.git cd firebase-admin-dotnet/FirebaseAdmin # Change into the FirebaseAdmin solution directory dotnet restore # Install dependencies ``` -------------------------------- ### List Users in Batches in C# Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Iterate through all users in paginated batches. This is useful for administrative tasks that require processing all users. ```csharp using FirebaseAdmin.Auth; using Google.Api.Gax; // List users page by page var pagedEnumerable = FirebaseAuth.DefaultInstance.ListUsersAsync(null); var responses = pagedEnumerable.AsRawResponses().GetAsyncEnumerator(); while (await responses.MoveNextAsync()) { ExportedUserRecords response = responses.Current; foreach (ExportedUserRecord user in response.Users) { Console.WriteLine($"User: {user.Uid}, Email: {user.Email}"); } } ``` ```csharp using FirebaseAdmin.Auth; // Iterate through all users one at a time var enumerator = FirebaseAuth.DefaultInstance .ListUsersAsync(new ListUsersOptions { PageSize = 100 }) .GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { ExportedUserRecord user = enumerator.Current; Console.WriteLine($"User: {user.Uid}"); } ``` -------------------------------- ### Add a NuGet Package Dependency Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/AGENTS.md Use the dotnet CLI to add a new package dependency to a project. Replace `` with the actual name of the NuGet package. ```bash dotnet add package ``` -------------------------------- ### Generate Email Action Links Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Create links for password resets, email verification, and email sign-in flows. Configure settings like redirect URLs and deep link parameters using `ActionCodeSettings`. These links are typically sent via a custom email service. ```csharp using FirebaseAdmin.Auth; var actionCodeSettings = new ActionCodeSettings() { Url = "https://www.example.com/checkout?cartId=1234", HandleCodeInApp = true, IosBundleId = "com.example.ios", AndroidPackageName = "com.example.android", AndroidInstallApp = true, AndroidMinimumVersion = "12", LinkDomain = "coolapp.page.link", }; // Generate password reset link string email = "user@example.com"; string passwordResetLink = await FirebaseAuth.DefaultInstance .GeneratePasswordResetLinkAsync(email, actionCodeSettings); Console.WriteLine($"Password reset link: {passwordResetLink}"); // Generate email verification link string verificationLink = await FirebaseAuth.DefaultInstance .GenerateEmailVerificationLinkAsync(email, actionCodeSettings); Console.WriteLine($"Verification link: {verificationLink}"); // Generate sign-in with email link string signInLink = await FirebaseAuth.DefaultInstance .GenerateSignInWithEmailLinkAsync(email, actionCodeSettings); Console.WriteLine($"Sign-in link: {signInLink}"); // Send these links via your own email service await SendCustomEmailAsync(email, "Reset Your Password", passwordResetLink); ``` -------------------------------- ### Manage Tenants for Multi-Tenant Applications Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Utilize the Firebase Admin .NET SDK to create, retrieve, update, list, and delete tenants for multi-tenant applications. This includes performing tenant-scoped operations like user creation. ```csharp using FirebaseAdmin.Auth; using FirebaseAdmin.Auth.Multitenancy; // Access TenantManager TenantManager tenantManager = FirebaseAuth.DefaultInstance.TenantManager; // Create a new tenant var createArgs = new TenantArgs() { DisplayName = "My Company Tenant", AllowPasswordSignUp = true, EnableEmailLinkSignIn = true, }; Tenant newTenant = await tenantManager.CreateTenantAsync(createArgs); Console.WriteLine($"Created tenant: {newTenant.TenantId}"); // Get tenant by ID Tenant tenant = await tenantManager.GetTenantAsync("tenant-id"); Console.WriteLine($"Tenant display name: {tenant.DisplayName}"); // Update tenant var updateArgs = new TenantArgs() { DisplayName = "Updated Company Name", AllowPasswordSignUp = false, }; Tenant updatedTenant = await tenantManager.UpdateTenantAsync("tenant-id", updateArgs); // List all tenants var enumerator = tenantManager.ListTenantsAsync(null).GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { Tenant t = enumerator.Current; Console.WriteLine($"Tenant: {t.TenantId}, Name: {t.DisplayName}"); } // Delete tenant await tenantManager.DeleteTenantAsync("tenant-id-to-delete"); // Perform tenant-scoped operations TenantAwareFirebaseAuth tenantAuth = tenantManager.AuthForTenant("tenant-id"); UserRecord tenantUser = await tenantAuth.CreateUserAsync(new UserRecordArgs() { Email = "tenant-user@example.com", Password = "password123", }); Console.WriteLine($"Created user {tenantUser.Uid} in tenant"); ``` -------------------------------- ### Retrieve User Data by Identifier Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Fetch user information using their UID, email, or phone number. For multiple users, use GetUsersAsync with a list of UserIdentifier objects. ```csharp using FirebaseAdmin.Auth; // Get user by UID UserRecord userByUid = await FirebaseAuth.DefaultInstance.GetUserAsync("some-uid"); Console.WriteLine($"User: {userByUid.Email}, Verified: {userByUid.EmailVerified}"); // Get user by email UserRecord userByEmail = await FirebaseAuth.DefaultInstance .GetUserByEmailAsync("user@example.com"); Console.WriteLine($"Found user: {userByEmail.Uid}"); // Get user by phone number UserRecord userByPhone = await FirebaseAuth.DefaultInstance .GetUserByPhoneNumberAsync("+11234567890"); Console.WriteLine($"Phone user: {userByPhone.Uid}"); // Bulk fetch multiple users with different identifiers GetUsersResult result = await FirebaseAuth.DefaultInstance.GetUsersAsync( new List { new UidIdentifier("uid1"), new EmailIdentifier("user2@example.com"), new PhoneIdentifier("+15555550003"), new ProviderIdentifier("google.com", "google_uid4"), }); Console.WriteLine("Successfully fetched user data:"); foreach (UserRecord user in result.Users) { Console.WriteLine($" User: {user.Uid}, Email: {user.Email}"); } Console.WriteLine("Unable to find users for these identifiers:"); foreach (UserIdentifier uid in result.NotFound) { Console.WriteLine($" {uid}"); } ``` -------------------------------- ### Import Federated Users in C# Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Import users who authenticate through federated identity providers like Google. This method does not require password hashes. ```csharp using FirebaseAdmin.Auth; // Import users without passwords (federated users) var federatedUsers = new List() { new ImportUserRecordArgs() { Uid = "google-user-uid", DisplayName = "Google User", Email = "googleuser@gmail.com", PhotoUrl = "https://lh3.googleusercontent.com/photo.jpg", EmailVerified = true, CustomClaims = new Dictionary() { { "provider", "google" } }, UserProviders = new List { new UserProvider() { Uid = "google-uid-12345", Email = "googleuser@gmail.com", DisplayName = "Google User", ProviderId = "google.com", }, }, }, }; UserImportResult fedResult = await FirebaseAuth.DefaultInstance .ImportUsersAsync(federatedUsers); ``` -------------------------------- ### Create Custom Tokens with Firebase Admin .NET Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Generate custom authentication tokens for Firebase client SDKs. Supports adding custom claims to the token. ```csharp using FirebaseAdmin.Auth; // Create a simple custom token var uid = "some-uid"; string customToken = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid); Console.WriteLine($"Custom token: {customToken}"); // Create a custom token with additional claims var additionalClaims = new Dictionary() { { "premiumAccount", true }, { "role", "admin" }, { "accessLevel", 5 } }; string customTokenWithClaims = await FirebaseAuth.DefaultInstance .CreateCustomTokenAsync(uid, additionalClaims); // Send this token to your client app for signInWithCustomToken() ``` -------------------------------- ### Generate Detailed Code Coverage Report Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/CONTRIBUTING.md To generate a detailed HTML code coverage report, first run tests with coverage enabled and specify the output format. Then, use a tool like Report Generator with the generated coverage data. ```bash $ dotnet test FirebaseAdmin.Tests /p:CollectCoverage=true /p:CoverletOutputFormat=opencover $ dotnet path/to/ReportGenerator.dll -reports:./FirebaseAdmin.Tests/coverage.opencover.xml -targetdir:./reports ``` -------------------------------- ### List All OIDC Providers Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Iterate through all configured OIDC providers using ListOidcProviderConfigsAsync. This method returns an async enumerator for efficient handling of potentially large lists. ```csharp // List all OIDC providers var enumerator = FirebaseAuth.DefaultInstance .ListOidcProviderConfigsAsync(null) .GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { OidcProviderConfig provider = enumerator.Current; Console.WriteLine($"Provider: {provider.ProviderId}"); } ``` -------------------------------- ### Run Unit Tests with Code Coverage Source: https://github.com/firebase/firebase-admin-dotnet/blob/main/CONTRIBUTING.md Enable code coverage collection when running unit tests by setting the `CollectCoverage` property to `true`. This provides a summary of code coverage. ```bash $ dotnet test FirebaseAdmin.Tests /p:CollectCoverage=true ``` -------------------------------- ### Create and Verify Session Cookies Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Use these methods to create a session cookie from an ID token and verify its validity. Ensure the Firebase Admin SDK is initialized. The session cookie is appended to the response and can be retrieved from request cookies. ```csharp using FirebaseAdmin.Auth; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; // Create a session cookie from ID token [HttpPost("sessionLogin")] public async Task Login([FromBody] LoginRequest request) { var options = new SessionCookieOptions() { ExpiresIn = TimeSpan.FromDays(5), }; try { string sessionCookie = await FirebaseAuth.DefaultInstance .CreateSessionCookieAsync(request.IdToken, options); var cookieOptions = new CookieOptions() { Expires = DateTimeOffset.UtcNow.Add(options.ExpiresIn), HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict }; Response.Cookies.Append("session", sessionCookie, cookieOptions); return Ok(new { status = "success" }); } catch (FirebaseAuthException) { return Unauthorized("Failed to create session cookie"); } } // Verify session cookie [HttpGet("profile")] public async Task Profile() { var sessionCookie = Request.Cookies["session"]; if (string.IsNullOrEmpty(sessionCookie)) { return Redirect("/login"); } try { bool checkRevoked = true; var decodedToken = await FirebaseAuth.DefaultInstance .VerifySessionCookieAsync(sessionCookie, checkRevoked); return Ok(new { uid = decodedToken.Uid, claims = decodedToken.Claims }); } catch (FirebaseAuthException) { return Redirect("/login"); } } // Logout and revoke session [HttpPost("sessionLogout")] public async Task Logout() { var sessionCookie = Request.Cookies["session"]; try { var decodedToken = await FirebaseAuth.DefaultInstance .VerifySessionCookieAsync(sessionCookie); await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(decodedToken.Uid); } catch (FirebaseAuthException) { } Response.Cookies.Delete("session"); return Redirect("/login"); } ``` -------------------------------- ### Subscribe and Unsubscribe Device Tokens to FCM Topics Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Manage device subscriptions to Firebase Cloud Messaging topics. This involves providing a list of registration tokens and the topic name to either subscribe or unsubscribe devices. ```csharp using FirebaseAdmin.Messaging; var registrationTokens = new List() { "token1", "token2", "token3", }; // Subscribe devices to a topic var subscribeResponse = await FirebaseMessaging.DefaultInstance .SubscribeToTopicAsync(registrationTokens, "news"); Console.WriteLine($"{subscribeResponse.SuccessCount} tokens subscribed successfully"); Console.WriteLine($"{subscribeResponse.FailureCount} tokens failed"); foreach (var error in subscribeResponse.Errors) { Console.WriteLine($"Error at index {error.Index}: {error.Reason}"); } // Unsubscribe devices from a topic var unsubscribeResponse = await FirebaseMessaging.DefaultInstance .UnsubscribeFromTopicAsync(registrationTokens, "news"); Console.WriteLine($"{unsubscribeResponse.SuccessCount} tokens unsubscribed successfully"); ``` -------------------------------- ### Verify ID Tokens in .NET Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Verify Firebase ID tokens from client applications to authenticate users on the backend. Includes options for checking token revocation and handling common errors. ```csharp using FirebaseAdmin.Auth; try { // Basic ID token verification string idToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."; FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance .VerifyIdTokenAsync(idToken); string uid = decodedToken.Uid; string email = decodedToken.Claims.ContainsKey("email") ? decodedToken.Claims["email"].ToString() : null; Console.WriteLine($"Verified user: {uid}, Email: {email}"); // Verify with revocation check (requires additional API call) bool checkRevoked = true; var verifiedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync( idToken, checkRevoked); Console.WriteLine($"Token valid, user: {verifiedToken.Uid}"); } catch (FirebaseAuthException ex) { if (ex.AuthErrorCode == AuthErrorCode.RevokedIdToken) { Console.WriteLine("Token has been revoked. User must re-authenticate."); } else if (ex.AuthErrorCode == AuthErrorCode.ExpiredIdToken) { Console.WriteLine("Token has expired."); } else { Console.WriteLine($"Token verification failed: {ex.Message}"); } } ``` -------------------------------- ### Update User Account Properties Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Modify an existing user's properties by providing the Uid and the new values in UserRecordArgs. Ensure Uid is set for updates. ```csharp using FirebaseAdmin.Auth; UserRecordArgs updateArgs = new UserRecordArgs() { Uid = "existing-user-uid", // Required for updates Email = "newemail@example.com", PhoneNumber = "+11234567890", EmailVerified = true, Password = "newSecurePassword456", DisplayName = "Jane Doe", PhotoUrl = "https://example.com/photos/janedoe.png", Disabled = false, }; try { UserRecord updatedUser = await FirebaseAuth.DefaultInstance.UpdateUserAsync(updateArgs); Console.WriteLine($"Successfully updated user: {updatedUser.Uid}"); Console.WriteLine($"New email: {updatedUser.Email}"); Console.WriteLine($"Email verified: {updatedUser.EmailVerified}"); } catch (FirebaseAuthException ex) { Console.WriteLine($"Error updating user: {ex.Message}"); } ``` -------------------------------- ### Send FCM Multicast Message to Multiple Tokens Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Send a single message to multiple devices simultaneously using their registration tokens. This is more efficient than sending individual messages to each token. ```csharp using FirebaseAdmin.Messaging; // Send to multiple tokens (multicast) var registrationTokens = new List() { "token1", "token2", "token3", }; var multicastMessage = new MulticastMessage() { Tokens = registrationTokens, Data = new Dictionary() { { "score", "850" }, { "time", "2:45" }, }, Notification = new Notification() { Title = "New High Score!", Body = "Check out the leaderboard", }, }; var multicastResponse = await FirebaseMessaging.DefaultInstance .SendEachForMulticastAsync(multicastMessage); // Handle failures if (multicastResponse.FailureCount > 0) { var failedTokens = new List(); for (var i = 0; i < multicastResponse.Responses.Count; i++) { if (!multicastResponse.Responses[i].IsSuccess) { failedTokens.Add(registrationTokens[i]); Console.WriteLine($"Failed: {multicastResponse.Responses[i].Exception.Message}"); } } Console.WriteLine($"Failed tokens: {string.Join(", ", failedTokens)}"); } ``` -------------------------------- ### Delete User Accounts Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Remove a single user by their UID or delete multiple users (up to 1000) using DeleteUsersAsync. The latter returns counts of successful and failed deletions. ```csharp using FirebaseAdmin.Auth; // Delete a single user await FirebaseAuth.DefaultInstance.DeleteUserAsync("user-uid-to-delete"); Console.WriteLine("Successfully deleted user."); // Bulk delete multiple users (up to 1000) DeleteUsersResult result = await FirebaseAuth.DefaultInstance.DeleteUsersAsync( new List { "uid1", "uid2", "uid3", }); Console.WriteLine($"Successfully deleted {result.SuccessCount} users."); Console.WriteLine($"Failed to delete {result.FailureCount} users."); foreach (ErrorInfo err in result.Errors) { Console.WriteLine($"Error #{err.Index}, reason: {err.Reason}"); } ``` -------------------------------- ### Set Custom User Claims in C# Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Assign custom key-value pairs to a user's Firebase ID token for use in security rules. Claims can be set, read, and removed. ```csharp using FirebaseAdmin.Auth; string uid = "user-uid"; // Set admin privileges var claims = new Dictionary() { { "admin", true }, { "accessLevel", 10 }, { "department", "engineering" } }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims); Console.WriteLine("Custom claims set successfully."); // Verify custom claims from ID token string idToken = "user-id-token"; FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken); if (decoded.Claims.TryGetValue("admin", out object isAdmin) && (bool)isAdmin) { Console.WriteLine("User has admin privileges"); } // Read custom claims from user record UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); if (user.CustomClaims.TryGetValue("accessLevel", out object level)) { Console.WriteLine($"User access level: {level}"); } // Remove all custom claims by setting to null await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, null); ``` -------------------------------- ### Send FCM Message to a Topic Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Send a message to all devices subscribed to a specific topic. Topics can be referenced directly or with the '/topics/' prefix. ```csharp using FirebaseAdmin.Messaging; // Send to a topic var topicMessage = new Message() { Data = new Dictionary() { { "score", "850" }, { "time", "2:45" }, }, Topic = "highScores", // Can also use "/topics/highScores" }; response = await FirebaseMessaging.DefaultInstance.SendAsync(topicMessage); Console.WriteLine($"Sent to topic: {response}"); ``` -------------------------------- ### Update SAML Provider Certificates Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Update the X.509 certificates for an existing SAML provider. This is crucial for maintaining security when certificates expire or are rotated. ```csharp // Update SAML provider certificates var updateArgs = new SamlProviderConfigArgs() { ProviderId = "saml.myProvider", X509Certificates = new List() { "-----BEGIN CERTIFICATE-----\nNEW_CERT...\n-----END CERTIFICATE-----", }, }; SamlProviderConfig updated = await FirebaseAuth.DefaultInstance .UpdateProviderConfigAsync(updateArgs); ``` -------------------------------- ### Send FCM Message with a Condition Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Send a message to devices that match a given condition, which is a boolean expression on topics. This allows for targeted messaging based on topic subscriptions. ```csharp using FirebaseAdmin.Messaging; // Send with condition (boolean logic on topics) var conditionMessage = new Message() { Notification = new Notification() { Title = "$GOOG up 1.43% on the day", Body = "$GOOG gained 11.80 points to close at 835.67", }, Condition = "'stock-GOOG' in topics || 'industry-tech' in topics", }; response = await FirebaseMessaging.DefaultInstance.SendAsync(conditionMessage); Console.WriteLine($"Sent with condition: {response}"); ``` -------------------------------- ### Update OIDC Provider Configuration Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Modify an existing OIDC provider's settings using UpdateProviderConfigAsync. Provide a new OidcProviderConfigArgs object with the desired changes. ```csharp // Update OIDC provider var updateArgs = new OidcProviderConfigArgs() { ProviderId = "oidc.myProvider", DisplayName = "Updated OIDC Provider", Enabled = true, ClientId = "NEW_CLIENT_ID", Issuer = "https://oidc.example.com", }; OidcProviderConfig updated = await FirebaseAuth.DefaultInstance .UpdateProviderConfigAsync(updateArgs); ``` -------------------------------- ### Send Batch FCM Messages (SendEachAsync) Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Efficiently send multiple individual messages in a single batch request, up to 500 messages. This method returns success and failure counts. ```csharp using FirebaseAdmin.Messaging; // Send multiple individual messages var messages = new List() { new Message() { Notification = new Notification() { Title = "Price drop", Body = "5% off all electronics", }, Token = "device-token-1", }, new Message() { Notification = new Notification() { Title = "Price drop", Body = "2% off all books", }, Topic = "readers-club", }, }; var response = await FirebaseMessaging.DefaultInstance.SendEachAsync(messages); Console.WriteLine($"{response.SuccessCount} messages were sent successfully"); Console.WriteLine($"{response.FailureCount} messages failed"); ``` -------------------------------- ### Send FCM Message to a Specific Device Token Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Use this to send a message directly to a device identified by its registration token. Ensure the token is valid. ```csharp using FirebaseAdmin.Messaging; // Send to a specific device token var tokenMessage = new Message() { Data = new Dictionary() { { "score", "850" }, { "time", "2:45" }, }, Notification = new Notification() { Title = "Game Update", Body = "Your score has been updated!", }, Token = "device-registration-token", }; string response = await FirebaseMessaging.DefaultInstance.SendAsync(tokenMessage); Console.WriteLine($"Successfully sent message: {response}"); ``` -------------------------------- ### Send Cross-Platform Message with Platform-Specific Overrides Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Construct a Firebase Cloud Messaging message with common notification details and platform-specific configurations for Android, iOS (APNs), and Webpush. This allows tailoring the message delivery and appearance for each platform. ```csharp using FirebaseAdmin.Messaging; // Cross-platform message with platform-specific overrides var message = new Message { // Common notification for all platforms Notification = new Notification() { Title = "$GOOG up 1.43% on the day", Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.", }, // Android-specific configuration Android = new AndroidConfig() { TimeToLive = TimeSpan.FromHours(1), Priority = Priority.High, Notification = new AndroidNotification() { Icon = "stock_ticker_update", Color = "#f45342", Sound = "default", ClickAction = "OPEN_STOCK_ACTIVITY", }, }, // iOS APNs configuration Apns = new ApnsConfig() { Headers = new Dictionary() { { "apns-priority", "10" }, { "apns-push-type", "alert" }, }, Aps = new Aps() { Alert = new ApsAlert() { Title = "$GOOG up 1.43% on the day", Body = "$GOOG gained 11.80 points", }, Badge = 42, Sound = "default", }, }, // Web push configuration Webpush = new WebpushConfig() { Notification = new WebpushNotification() { Title = "$GOOG up 1.43% on the day", Body = "$GOOG gained 11.80 points to close at 835.67", Icon = "https://my-server/icon.png", }, FcmOptions = new WebpushFcmOptions() { Link = "https://example.com/stocks/GOOG", }, }, Topic = "industry-tech", }; string response = await FirebaseMessaging.DefaultInstance.SendAsync(message); ``` -------------------------------- ### Delete OIDC Provider Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Remove an OIDC provider configuration by specifying its ProviderId. This action is irreversible. ```csharp // Delete OIDC provider await FirebaseAuth.DefaultInstance.DeleteProviderConfigAsync("oidc.myProvider"); ``` -------------------------------- ### Delete SAML Provider Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Remove a SAML provider configuration using its ProviderId. This operation permanently deletes the provider settings. ```csharp // Delete SAML provider await FirebaseAuth.DefaultInstance.DeleteProviderConfigAsync("saml.myProvider"); ``` -------------------------------- ### Perform a Dry Run for an FCM Message Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Validate a message payload without actually sending it to devices. This is useful for testing message configurations. ```csharp using FirebaseAdmin.Messaging; // Dry run to validate message without sending response = await FirebaseMessaging.DefaultInstance.SendAsync(tokenMessage, dryRun: true); Console.WriteLine($"Dry run successful: {response}"); ``` -------------------------------- ### Revoke User Refresh Tokens Source: https://context7.com/firebase/firebase-admin-dotnet/llms.txt Invalidate all existing sessions for a user by revoking their refresh tokens. This requires the user's UID. When verifying tokens, set `checkRevoked: true` to ensure the token has not been revoked. ```csharp using FirebaseAdmin.Auth; string uid = "user-uid"; // Revoke all refresh tokens await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(uid); // Get the updated user to see when tokens were revoked var user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine($"Tokens revoked at: {user.TokensValidAfterTimestamp}"); // When verifying tokens, check for revocation try { var decodedToken = await FirebaseAuth.DefaultInstance .VerifyIdTokenAsync(idToken, checkRevoked: true); Console.WriteLine($"Token is valid for user: {decodedToken.Uid}"); } catch (FirebaseAuthException ex) { if (ex.AuthErrorCode == AuthErrorCode.RevokedIdToken) { Console.WriteLine("Token was revoked. User must sign in again."); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.