C
C#•6d ago
Zoli

How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?

In my Maui application, I have successfully implemented email/password authentication and real-time data synchronization. To filter data so that only the logged-in user's relevant documents are shown, should I add a new property (e.g., ownerId) to each document and perform the filtering on the client side? I saw WhereEqualTo could filter but is this the right approcach to filter on the client by the ownerid? But it means I need to store the userId on the client, is it safe? (I saw some relevant questions but they are 6-10 years old and not maui/.net related if matters at all)
5 Replies
Mayor McCheese
Mayor McCheese•6d ago
Can you use firebase custom authentication? I don't know what the support for firebase custom authentication is in the existing sdks, it didn't quite exist before and needed some massaging in code to work. This was about 3 years back though. I can try and dig up my old code. if you think it'll help you.
Zoli
ZoliOP•6d ago
That would be amazing 😄
Mayor McCheese
Mayor McCheese•5d ago
It'll take a bit, I've got to find it on an old drive and redact it a bit Actually honestly checking chat gpt a bit seems to have changed that I had to do manually.
To implement Custom Authorization in Firebase using C#, you can achieve it by leveraging Firebase Admin SDK for C# to generate custom tokens and set custom claims. Here’s a step-by-step guide:

Step 1: Set Up Firebase Admin SDK in C#
1. Install the Firebase Admin SDK using NuGet:

dotnet add package FirebaseAdmin


2. Download your Firebase Service Account Key from the Firebase Console:
• Go to Project Settings > Service accounts > Generate new private key.
• Save the JSON file securely.

Step 2: Initialize Firebase Admin SDK

Create a Firebase Admin App to interact with Firebase services.

using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;

public class FirebaseService
{
public FirebaseService()
{
if (FirebaseApp.DefaultInstance == null)
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/your-service-account-file.json")
});
}
}
}

Step 3: Generate Custom Tokens

To authenticate users via a Custom Token, you need to generate a token and send it to the client.

using FirebaseAdmin.Auth;

public class CustomTokenService
{
public async Task<string> GenerateCustomToken(string uid, Dictionary<string, object> customClaims = null)
{
var token = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, customClaims);
return token;
}
}

Usage Example:

var firebaseService = new CustomTokenService();
var customClaims = new Dictionary<string, object>
{
{ "role", "admin" }, // Set a custom role for the user
{ "canEdit", true }
};

string customToken = await firebaseService.GenerateCustomToken("user-unique-id", customClaims);
Console.WriteLine($"Custom Token: {customToken}");

Step 4: Authenticate on the Client-Side (Firebase Client SDK)

Send the custom token to your client application (e.g., mobile, web), and sign in using the Firebase Client SDK.

Example in a C# client (using Firebase Client SDK):

using Firebase.Auth;

// Firebase project credentials
string apiKey = "YOUR_FIREBASE_API_KEY";
string customToken = "RECEIVED_CUSTOM_TOKEN_FROM_SERVER";

var auth = new FirebaseAuthProvider(new FirebaseConfig(apiKey));
var authLink = await auth.SignInWithCustomTokenAsync(customToken);

Console.WriteLine("User ID: " + authLink.User.LocalId);
Console.WriteLine("ID Token: " + authLink.FirebaseToken);

Step 5: Set Custom Claims

Custom claims allow you to assign roles or permissions to users that you can validate in Firebase Security Rules.

Set Custom Claims for a User

using FirebaseAdmin.Auth;

public async Task SetCustomClaims(string uid, Dictionary<string, object> claims)
{
await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims);
Console.WriteLine("Custom claims set for user.");
}

Usage Example:

var claims = new Dictionary<string, object>
{
{ "role", "editor" },
{ "accessLevel", 3 }
};

await SetCustomClaims("user-unique-id", claims);

Step 6: Secure Resources Using Firebase Rules

In Firebase (e.g., Firestore, Realtime Database), use custom claims to enforce rules.

Example Firestore Rule:

service cloud.firestore {
match /databases/{database}/documents {
match /protected/{docId} {
allow read, write: if request.auth.token.role == "admin";
}
}
}

Summary

By following these steps:
1. Generate custom tokens using the Firebase Admin SDK in C#.
2. Set custom claims to define user roles and permissions.
3. Secure access using Firebase Security Rules.
4. Authenticate on the client-side with the custom token.

This approach ensures you have fine-grained control over user authorization in your Firebase project. If you need further details or a specific setup, let me know!
To implement Custom Authorization in Firebase using C#, you can achieve it by leveraging Firebase Admin SDK for C# to generate custom tokens and set custom claims. Here’s a step-by-step guide:

Step 1: Set Up Firebase Admin SDK in C#
1. Install the Firebase Admin SDK using NuGet:

dotnet add package FirebaseAdmin


2. Download your Firebase Service Account Key from the Firebase Console:
• Go to Project Settings > Service accounts > Generate new private key.
• Save the JSON file securely.

Step 2: Initialize Firebase Admin SDK

Create a Firebase Admin App to interact with Firebase services.

using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;

public class FirebaseService
{
public FirebaseService()
{
if (FirebaseApp.DefaultInstance == null)
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/your-service-account-file.json")
});
}
}
}

Step 3: Generate Custom Tokens

To authenticate users via a Custom Token, you need to generate a token and send it to the client.

using FirebaseAdmin.Auth;

public class CustomTokenService
{
public async Task<string> GenerateCustomToken(string uid, Dictionary<string, object> customClaims = null)
{
var token = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, customClaims);
return token;
}
}

Usage Example:

var firebaseService = new CustomTokenService();
var customClaims = new Dictionary<string, object>
{
{ "role", "admin" }, // Set a custom role for the user
{ "canEdit", true }
};

string customToken = await firebaseService.GenerateCustomToken("user-unique-id", customClaims);
Console.WriteLine($"Custom Token: {customToken}");

Step 4: Authenticate on the Client-Side (Firebase Client SDK)

Send the custom token to your client application (e.g., mobile, web), and sign in using the Firebase Client SDK.

Example in a C# client (using Firebase Client SDK):

using Firebase.Auth;

// Firebase project credentials
string apiKey = "YOUR_FIREBASE_API_KEY";
string customToken = "RECEIVED_CUSTOM_TOKEN_FROM_SERVER";

var auth = new FirebaseAuthProvider(new FirebaseConfig(apiKey));
var authLink = await auth.SignInWithCustomTokenAsync(customToken);

Console.WriteLine("User ID: " + authLink.User.LocalId);
Console.WriteLine("ID Token: " + authLink.FirebaseToken);

Step 5: Set Custom Claims

Custom claims allow you to assign roles or permissions to users that you can validate in Firebase Security Rules.

Set Custom Claims for a User

using FirebaseAdmin.Auth;

public async Task SetCustomClaims(string uid, Dictionary<string, object> claims)
{
await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims);
Console.WriteLine("Custom claims set for user.");
}

Usage Example:

var claims = new Dictionary<string, object>
{
{ "role", "editor" },
{ "accessLevel", 3 }
};

await SetCustomClaims("user-unique-id", claims);

Step 6: Secure Resources Using Firebase Rules

In Firebase (e.g., Firestore, Realtime Database), use custom claims to enforce rules.

Example Firestore Rule:

service cloud.firestore {
match /databases/{database}/documents {
match /protected/{docId} {
allow read, write: if request.auth.token.role == "admin";
}
}
}

Summary

By following these steps:
1. Generate custom tokens using the Firebase Admin SDK in C#.
2. Set custom claims to define user roles and permissions.
3. Secure access using Firebase Security Rules.
4. Authenticate on the client-side with the custom token.

This approach ensures you have fine-grained control over user authorization in your Firebase project. If you need further details or a specific setup, let me know!
That's about what I did with a lot of other customizations for missing functionality If chat gpt is correct, that gap closed a lot
Zoli
ZoliOP•5d ago
Super, thanks. I will take a look, one question is it safe/secure to store firebase-service-account json on the Maui side?
Mayor McCheese
Mayor McCheese•5d ago
Yeah you don't want to do that, you'd want to store it in the server, create the custom auth token on the server side, and authenticate with the custom token on the Maui side with firebase. I'm not expert here and my recollection is from 2018 or so
Want results from more Discord servers?
Add your server