Comments (9)
var bytes = Convert.FromBase64String("base64");
var stream = new StreamContent(new MemoryStream(bytes)).ReadAsStream();
var auth = new FirebaseAuthProvider(new FirebaseConfig("api_key"));
var a = await auth.SignInWithEmailAndPasswordAsync("email", "password");
var cancellation = new CancellationTokenSource();
var action = new FirebaseStorage(
"bucket",
new FirebaseStorageOptions
{
AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
ThrowOnCancel = true,
})
.Child("folder")
.Child($"{"file_name"}.{"file_extension"}")
.PutAsync("stream", cancellation.Token);
from firebase-storage-dotnet.
Thank you but that's Regular Account (Service account doesn't have "email" or "password").
I'm talking about Service Account for which you get Private Key in .json format through Firebase Console.
e.g. I'm using it like this for RealtimeDatabase:
private static async Task<String> AuthenticateAsync(String privateKeyLocation)
{
GoogleCredential googleCredential = GoogleCredential.FromFile(privateKeyLocation)
.CreateScoped(
"https://www.googleapis.com/auth/firebase", // RTDB.
"https://www.googleapis.com/auth/userinfo.email", // RTDB
"https://www.googleapis.com/auth/identitytoolkit", // User management
"https://www.googleapis.com/auth/devstorage.full_control", // Cloud Storage
"https://www.googleapis.com/auth/cloud-platform", // Cloud Firestore
"https://www.googleapis.com/auth/datastore"
);
return await googleCredential.UnderlyingCredential.GetAccessTokenForRequestAsync();
}
But, I'm still getting (403) Forbidden as StatusCode of Response (for Storage, Realtime Database works just fine).
This is rest of Code which is using AuthenticateAsync in case I'm missing something there:
FirebaseStorageTask firebaseStorageTask = new FirebaseStorage(bucketURL, new FirebaseStorageOptions
{
AuthTokenAsyncFactory = () => AuthenticateAsync(serviceAccountPrivateKeyLocation)
})
.Child(@"AppImages")
.Child(Path.GetFileName(filePath))
.PutAsync(stream);
from firebase-storage-dotnet.
Thank you but that's Regular Account (Service account doesn't have "email" or "password").
I'm talking about Service Account for which you get Private Key in .json format through Firebase Console.e.g. I'm using it like this for RealtimeDatabase:
private static async Task<String> AuthenticateAsync(String privateKeyLocation) { GoogleCredential googleCredential = GoogleCredential.FromFile(privateKeyLocation) .CreateScoped( "https://www.googleapis.com/auth/firebase", // RTDB. "https://www.googleapis.com/auth/userinfo.email", // RTDB "https://www.googleapis.com/auth/identitytoolkit", // User management "https://www.googleapis.com/auth/devstorage.full_control", // Cloud Storage "https://www.googleapis.com/auth/cloud-platform", // Cloud Firestore "https://www.googleapis.com/auth/datastore" );
return await googleCredential.UnderlyingCredential.GetAccessTokenForRequestAsync();
}But, I'm still getting (403) Forbidden as StatusCode of Response (for Storage, Realtime Database works just fine).
This is rest of Code which is using AuthenticateAsync in case I'm missing something there:
FirebaseStorageTask firebaseStorageTask = new FirebaseStorage(bucketURL, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => AuthenticateAsync(serviceAccountPrivateKeyLocation) }) .Child(@"AppImages") .Child(Path.GetFileName(filePath)) .PutAsync(stream);
I found a bit of a workaround using this and the FirebaseAdmin SDK, it could be improved, but it's a good start.
(Make sure you Initialize the Admin SDK with FirebaseApp.Create()
before running the code below)
string token = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.CreateCustomTokenAsync("[your server id, can be anything]", developerClaims: new Dictionary<string, object>()
{
{ "server", true } // Adds a "server: true" claim to the token
});
FirebaseAuthProvider firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig("[Firebase web API key]"));
var authLink = await firebaseAuthProvider.SignInWithCustomTokenAsync(token);
return authLink.FirebaseToken; // This is the JWT token
from firebase-storage-dotnet.
I'm still getting same 403 error.
I've tried it like this:
FirebaseApp firebaseApp = FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromFile(serviceAccountPrivateKeyLocation),
ProjectId = projectID
});
string token = await FirebaseAdmin.Auth.FirebaseAuth.GetAuth(firebaseApp).CreateCustomTokenAsync(Guid.NewGuid().ToString(), developerClaims: new Dictionary<string, object>()
{
{ "server", true } // Adds a "server: true" claim to the token
});
FirebaseAuthProvider firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey));
var authLink = await firebaseAuthProvider.SignInWithCustomTokenAsync(token);
return authLink.FirebaseToken; // This is the JWT token
from firebase-storage-dotnet.
I've faced the same problem yesterday and found a good (and simple) solution just now.
Assuming you're using the AdminSDK (nuget) you can get a valid JWT Token with¹:
FirebaseAuth.DefaultInstance.CreateCustomTokenAsync("SOME_UID")
If you are still getting a 403 error, take a look at this SO answer
Sample:
var options = new FirebaseStorageOptions {
AuthTokenAsyncFactory = () => FirebaseAuth.DefaultInstance.CreateCustomTokenAsync("SOME_UID")
};
new FirebaseStorage("PROJECT.appspot.com", options)
.Child("FILE_NAME")
.PutAsync(SOME_STREAM);
Sources:
1: https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_the_firebase_admin_sdk
2: https://developers.google.com/identity/protocols/oauth2/service-account#jwt-auth
from firebase-storage-dotnet.
@marko-mihalic have you found a solution maybe?
from firebase-storage-dotnet.
@caneva20 thank you, I'll try with rule separation mentioned in this SO answer when/if I get back to it.
@longa78 I didn't, we decided not to use Firebase Storage after all.
from firebase-storage-dotnet.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
from firebase-storage-dotnet.
Closing the issue due to inactivity. Feel free to re-open
from firebase-storage-dotnet.
Related Issues (20)
- Multiple Images Upload HOT 2
- List all files HOT 15
- progresschanged event not working with videos HOT 2
- Upload to a particular folder HOT 2
- .net core support HOT 2
- File getting deleted even with rule auth !=null HOT 2
- GetDownloadUrlAsync fails with 400 HOT 2
- 400 Bad request using Webclient and download URL HOT 2
- Response Data of N/A HOT 3
- token is invalid HOT 2
- how can i generate apikey HOT 2
- uploadTask.Progress.ProgressChanged(sender, args) always returns 100% on IOS HOT 1
- how can set meta data when uploading an image HOT 1
- Creating and removing subfolders in firebase storage HOT 1
- Getting meta data of all files on particular folder of Firebase Storage HOT 3
- Multiple Users editing file Concurrently on Firebase Storage
- Execption when you upload a img
- How To Delete File ??
- Firebase storage List function
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from firebase-storage-dotnet.