Mayor McCheese
Mayor McCheese
Explore posts from servers
CC#
Created by David on 12/17/2024 in #help
MSBuild Condition for Design-Time and Compile-Time
Some more advanced DI containers do offer some things that fody and postsharp ( and other weavers ) offer, but at a performance cost, sometimes a high performance cost. Back in the day things like caching method results were pretty popular. For example:
[CacheResult(key = "GetPeopleResult", expiration = "30m")]
public List<Person> GetPeople()
{
return dbContext.People.ToList();
}

[CacheResult(key = "GetPersonResult", expiration = "30m")]
public Person? GetPerson(int id)
{
return dbContext.People.FirstOrDefault(p=>p.Id == id);
}

[InvalidateCache(key = "GetPeopleResult")]
[InvalidateCache(key = "GetPersonResult")]
public void AddPerson(Person person)
{
dbContext.People.Add(person);
}

[InvalidateCache(key = "GetPeopleResult")]
[InvalidateCache(key = "GetPersonResult")]
public void DeletePerson(Person person)
{
dbContext.People.Delete(person);
}
[CacheResult(key = "GetPeopleResult", expiration = "30m")]
public List<Person> GetPeople()
{
return dbContext.People.ToList();
}

[CacheResult(key = "GetPersonResult", expiration = "30m")]
public Person? GetPerson(int id)
{
return dbContext.People.FirstOrDefault(p=>p.Id == id);
}

[InvalidateCache(key = "GetPeopleResult")]
[InvalidateCache(key = "GetPersonResult")]
public void AddPerson(Person person)
{
dbContext.People.Add(person);
}

[InvalidateCache(key = "GetPeopleResult")]
[InvalidateCache(key = "GetPersonResult")]
public void DeletePerson(Person person)
{
dbContext.People.Delete(person);
}
In this scenario, read operations are cached, and continue to be cached until a write operation is executed, or the time expires. Autofac supports things like this with some custom work. I don't think that's what you're looking for though.
7 replies
CC#
Created by David on 12/17/2024 in #help
MSBuild Condition for Design-Time and Compile-Time
Fody does il weaving and is frequently labeled under AOP, aspect oriented programming. Fody and postsharp both have weird licensing models
7 replies
CC#
Created by David on 12/17/2024 in #help
MSBuild Condition for Design-Time and Compile-Time
Can you state your goal? What are you trying to achieve?
7 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
I'm not expert here and my recollection is from 2018 or so
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
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.
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
If chat gpt is correct, that gap closed a lot
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
That's about what I did with a lot of other customizations for missing functionality
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
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!
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
Actually honestly checking chat gpt a bit seems to have changed that I had to do manually.
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
It'll take a bit, I've got to find it on an old drive and redact it a bit
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
if you think it'll help you.
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
I can try and dig up my old code.
13 replies
CC#
Created by Zoli on 12/16/2024 in #help
How to Filter Firebase Real-Time Data for the Logged-In User in a Maui Application?
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.
13 replies
CC#
Created by TheUnquiet on 12/14/2024 in #help
Jwt authorization returning 401 every time
You can configure swagger for oath as well
4 replies
CC#
Created by sudfhs on 12/14/2024 in #help
What is the best way to edit a form loaded from Assembly?
Form has controls collection
2 replies
CC#
Created by Drox on 12/8/2024 in #help
1 Error idk how fixe it
probably that
6 replies
CC#
Created by Drox on 12/8/2024 in #help
1 Error idk how fixe it
int moyenne = NB_QUESTIONS / 2;
6 replies
CC#
Created by mwc on 11/29/2024 in #help
Search object Inner list for value
@mtreit .ToList()
13 replies
CC#
Created by morry329# on 11/29/2024 in #help
✅ always gets the invalid data received
$.ajax({
type: "POST",
url: "@Url.Action("Update", "Home")",
data: {
ListingId: id,
ListingName_DTO: newName,
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() // Anti-forgery token
},
$.ajax({
type: "POST",
url: "@Url.Action("Update", "Home")",
data: {
ListingId: id,
ListingName_DTO: newName,
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() // Anti-forgery token
},
if (updatedUserModelRef == null || updatedUserModelRef.ListingName == null)
if (updatedUserModelRef == null || updatedUserModelRef.ListingName == null)
You have no ListingName, it's ListingName_DTO in js.
2 replies
CC#
Created by deveric on 11/25/2024 in #help
Hello, guys!
there's a lot of variables
11 replies