### Create Custom Token with Claims (Java) Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens This Java example shows how to create a custom token with additional claims, such as 'premiumAccount', which can be used in security rules. ```java String uid = "some-uid"; Map additionalClaims = new HashMap(); additionalClaims.put("premiumAccount", true); String customToken = FirebaseAuth.getInstance() .createCustomToken(uid, additionalClaims); // Send token back to client ``` -------------------------------- ### Sign in with Custom Token (C++ SDK) Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Example of signing in with a custom token using the Firebase C++ SDK. ```cpp firebase::Future result = auth->SignInWithCustomToken(custom_token); ``` -------------------------------- ### Initialize ActionCodeSettings in Go Source: https://firebase.google.com/docs/auth/admin/email-action-links Instantiate ActionCodeSettings in Go for email action links. This example configures the continue URL, in-app handling, and platform-specific settings for iOS and Android, utilizing a dynamic link domain. ```go actionCodeSettings := &auth.ActionCodeSettings{ URL: "https://www.example.com/checkout?cartId=1234", HandleCodeInApp: true, IOSBundleID: "com.example.ios", AndroidPackageName: "com.example.android", AndroidInstallApp: true, AndroidMinimumVersion: "12", DynamicLinkDomain: "coolapp.page.link", } ``` -------------------------------- ### Import Users with PBKDF2_SHA256 Hashing (Python) Source: https://firebase.google.com/docs/auth/admin/import-users Python example for importing users with PBKDF2_SHA256 hashed passwords. The password hash and salt should be byte strings. The number of hashing rounds is a required parameter. ```python users = [ auth.ImportUserRecord( uid='some-uid', email='user@example.com', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=100000) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) ``` -------------------------------- ### Import Users with Scrypt Hash (C#) Source: https://firebase.google.com/docs/auth/admin/import-users?hl=es-419 Import users with Scrypt-hashed passwords in C#. This example uses ASCII encoding for byte conversion of hash parameters. ```csharp try { var users = new List() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. Hash = new Scrypt() { Key = Encoding.ASCII.GetBytes("base64-secret"), SaltSeparator = Encoding.ASCII.GetBytes("base64-salt-separator"), Rounds = 8, MemoryCost = 14, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } ``` -------------------------------- ### Realtime Database Rules with Custom Claims Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Example Realtime Database rules demonstrating how to use custom claims included in the custom token to control access. ```json { "rules": { "premiumContent": { ".read": "auth.token.premiumAccount === true" } } } ``` -------------------------------- ### Generate Email Sign-In Link (C#) Source: https://firebase.google.com/docs/auth/admin/email-action-links An asynchronous C# example for generating an email sign-in link. This requires the Firebase Admin SDK to be initialized and `actionCodeSettings` to be provided. ```csharp var email = "user@example.com"; var link = await FirebaseAuth.DefaultInstance.GenerateSignInWithEmailLinkAsync( email, actionCodeSettings); // Construct email verification template, embed the link and send // using custom SMTP server. SendCustomEmail(email, displayName, link); ``` -------------------------------- ### Get User by Email (C#) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches user details using their email address. This is an asynchronous operation. ```csharp UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserByEmailAsync(email); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}"); ``` -------------------------------- ### Cloud Storage Rules with Custom Claims Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Example Cloud Storage rules demonstrating how to use custom claims included in the custom token to control access. ```json service firebase.storage { match /b//o { match /premiumContent/{filename} { allow read, write: if request.auth.token.premiumAccount == true; } } } ``` -------------------------------- ### Get User by Email (Python) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches a user's record by their email. Ensure the email is the primary email associated with the account. ```python from firebase_admin import auth user = auth.get_user_by_email(email) print(f'Successfully fetched user data: {user.uid}') ``` -------------------------------- ### Generate Email Sign-In Link (Python) Source: https://firebase.google.com/docs/auth/admin/email-action-links A Python example for generating an email sign-in link. This requires the Firebase Admin SDK to be initialized and `action_code_settings` to be passed. ```python email = 'user@example.com' link = auth.generate_sign_in_with_email_link(email, action_code_settings) # Construct email from a template embedding the link, and send # using a custom SMTP server. send_custom_email(email, link) ``` -------------------------------- ### Get User by Email (Go) Source: https://firebase.google.com/docs/auth/admin/manage-users Retrieves user data using the provided email address. This method searches the main email only. ```go u, err := client.GetUserByEmail(ctx, email) if err != nil { log.Fatalf("error getting user by email %s: %v\n", email, err) } log.Printf("Successfully fetched user data: %v\n", u) ``` -------------------------------- ### Create Custom Token (Go) Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens This Go example demonstrates creating a custom token with a user ID. It requires initializing the Firebase app and obtaining an auth client. Tokens are valid for one hour. ```go client, err := app.Auth(context.Background()) if err != nil { log.Fatalf("error getting Auth client: %v\n", err) } token, err := client.CustomToken(ctx, "some-uid") if err != nil { log.Fatalf("error minting custom token: %v\n", err) } log.Printf("Got custom token: %v\n", token) auth.go ``` -------------------------------- ### Verify ID token in Go Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens For Go, first get the Auth client using `app.Auth(ctx)`. Then, use the `VerifyIDToken(ctx, idToken)` method to verify the token. Error handling is crucial for both steps. The verified token details can then be logged. ```go client, err := app.Auth(ctx) if err != nil { log.Fatalf("error getting Auth client: %v\n", err) } token, err := client.VerifyIDToken(ctx, idToken) if err != nil { log.Fatalf("error verifying ID token: %v\n", err) } log.Printf("Verified ID token: %v\n", token) ``` -------------------------------- ### Verify Session Cookie in Go Source: https://firebase.google.com/docs/auth/admin/manage-cookies Verify a session cookie in a Go HTTP handler. This example demonstrates checking for the cookie and handling verification errors. ```go return func(w http.ResponseWriter, r *http.Request) { // Get the ID token sent by the client cookie, err := r.Cookie("session") if err != nil { // Session cookie is unavailable. Force user to login. http.Redirect(w, r, "/login", http.StatusFound) return } // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. decoded, err := client.VerifySessionCookieAndCheckRevoked(r.Context(), cookie.Value) if err != nil { // Session cookie is invalid. Force user to login. http.Redirect(w, r, "/login", http.StatusFound) return } serveContentForUser(w, r, decoded) } ``` -------------------------------- ### Get User by Phone Number (Python) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches a user's record by their phone number. The phone number should be provided in E.164 format. ```python from firebase_admin import auth user = auth.get_user_by_phone_number(phone) ``` -------------------------------- ### Import Users Without Passwords in C# Source: https://firebase.google.com/docs/auth/admin/import-users This C# example imports users with custom claims and Google provider data. It utilizes the Firebase Admin SDK for .NET and includes robust error handling. ```csharp try { var users = new List() { new ImportUserRecordArgs() { Uid = "some-uid", DisplayName = "John Doe", Email = "johndoe@gmail.com", PhotoUrl = "http://www.example.com/12345678/photo.png", EmailVerified = true, PhoneNumber = "+11234567890", CustomClaims = new Dictionary() { { "admin", true }, // set this user as admin }, UserProviders = new List { new UserProvider() // user with Google provider { Uid = "google-uid", Email = "johndoe@gmail.com", DisplayName = "John Doe", PhotoUrl = "http://www.example.com/12345678/photo.png", ProviderId = "google.com", }, }, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users); foreach (ErrorInfo indexedError in result.Errors) { ``` -------------------------------- ### Set Custom Claims on User Creation (JavaScript) Source: https://firebase.google.com/docs/auth/admin/custom-claims Example of setting custom claims for a user upon signup using Cloud Functions. This ensures roles are assigned immediately and propagate to all sessions. ```javascript import { GoogleAuthProvider, signInWithPopup, getAuth, onAuthStateChanged } from "firebase/auth"; import { getDatabase, onValue, ref } from "firebase/database"; const auth = getAuth(); const database = getDatabase(); const provider = new GoogleAuthProvider(); signInWithPopup(auth, provider).catch(error => { console.log(error); }); let unsubscribeFn = null; let metadataRef = null; onAuthStateChanged(auth, user => { // Remove previous listener. if (unsubscribeFn) { unsubscribeFn(); } // On user login add new listener. if (user) { // Check if refresh is required. metadataRef = ref(database, 'metadata/' + user.uid + '/refreshTime'); // Subscribe new listener to changes on that node. unsubscribeFn = onValue(metadataRef, async (snapshot) => { // Force refresh to pick up the latest custom claims changes. // Note this is always triggered on first call. Further optimization could be // added to avoid the initial trigger when the token is issued and already contains // the latest claims. user.getIdToken(true); }); } }); ``` -------------------------------- ### Retrieve ID Token on C++ Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on C++. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```C++ firebase::auth::User user = auth->current_user(); if (user.is_valid()) { firebase::Future idToken = user.GetToken(true); // Send token to your backend via HTTPS // ... } ``` -------------------------------- ### Import Users with Standard Scrypt Hashing (Python) Source: https://firebase.google.com/docs/auth/admin/import-users Import users with scrypt-hashed passwords using Python. Password hash and salt should be byte strings. ```python users = [ auth.ImportUserRecord( uid='some-uid', email='user@example.com', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.standard_scrypt( memory_cost=1024, parallelization=16, block_size=8, derived_key_length=64) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) ``` -------------------------------- ### Retrieve ID Token on Web (JavaScript) Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on the web using JavaScript. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```JavaScript firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { // Send token to your backend via HTTPS // ... }).catch(function(error) { // Handle error }); ``` -------------------------------- ### Retrieve ID Token on Unity (C#) Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on Unity using C#. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```C# Firebase.Auth.FirebaseUser user = auth.CurrentUser; user.TokenAsync(true).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("TokenAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("TokenAsync encountered an error: " + task.Exception); return; } string idToken = task.Result; // Send token to your backend via HTTPS // ... }); ``` -------------------------------- ### Retrieve ID Token on Android (Java) Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on Android using Java. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```Java FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser(); mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener() { public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); // Send token to your backend via HTTPS // ... } else { // Handle error -> task.getException(); } } }); ``` -------------------------------- ### Import Users with Standard Scrypt Hashing (Go) Source: https://firebase.google.com/docs/auth/admin/import-users This Go snippet imports users with scrypt-hashed passwords. Password hash and salt must be byte slices. ```go users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("user@example.com"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.StandardScrypt{ MemoryCost: 1024, Parallelization: 16, BlockSize: 8, DerivedKeyLength: 64, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } ``` -------------------------------- ### Retrieve ID Token on iOS (Swift) Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on iOS using Swift. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```Swift let currentUser = FIRAuth.auth()?.currentUser currentUser?.getIDTokenForcingRefresh(true) { idToken, error in if let error = error { // Handle error return; } // Send token to your backend via HTTPS // ... } ``` -------------------------------- ### Retrieve ID Token on iOS (Objective-C) Source: https://firebase.google.com/docs/auth/admin/verify-id-tokens Get the current user's ID token on iOS using Objective-C. This token can be sent to your backend server for verification. Forcing a refresh ensures you get the latest token. ```Objective-C FIRUser *currentUser = [FIRAuth auth].currentUser; [currentUser getIDTokenForcingRefresh:YES completion:^(NSString *_Nullable idToken, NSError *_Nullable error) { if (error) { // Handle error return; } // Send token to your backend via HTTPS // ... }]; ``` -------------------------------- ### C#: Import users with Scrypt hash Source: https://firebase.google.com/docs/auth/admin/import-users?hl=tr Import users with a Scrypt password hash. Ensure that parameters like Key and SaltSeparator are correctly encoded as byte arrays. ```csharp var users = new List() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. Hash = new Scrypt() { Key = Encoding.ASCII.GetBytes("base64-secret"), SaltSeparator = Encoding.ASCII.GetBytes("base64-salt-separator"), Rounds = 8, MemoryCost = 14, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } ``` -------------------------------- ### Import Users with PBKDF2_SHA256 Hashing (Go) Source: https://firebase.google.com/docs/auth/admin/import-users This Go snippet imports users with PBKDF2_SHA256 hashed passwords. The password hash and salt are passed as byte slices. The number of rounds for the hashing algorithm must be specified. ```go users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("user@example.com"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.PBKDF2SHA256{ Rounds: 100000, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } ``` -------------------------------- ### Create Custom Token with Claims (Go) Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens This Go snippet demonstrates creating a custom token with custom claims, such as 'premiumAccount', which are useful for security rule evaluations. ```go client, err := app.Auth(context.Background()) if err != nil { log.Fatalf("error getting Auth client: %v\n", err) } claims := map[string]interface{}{ "premiumAccount": true, } token, err := client.CustomTokenWithClaims(ctx, "some-uid", claims) if err != nil { log.Fatalf("error minting custom token: %v\n", err) } log.Printf("Got custom token: %v\n", token) auth.go ``` -------------------------------- ### Get User by Email (Java) Source: https://firebase.google.com/docs/auth/admin/manage-users Retrieves user information using their email address. Note that only the main email can be searched. ```java UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getEmail()); ``` -------------------------------- ### List All Users (Java) Source: https://firebase.google.com/docs/auth/admin/manage-users Demonstrates two ways to list users in Java: iterating through pages and iterating through all users. Both methods retrieve users in batches. ```java // Start listing users from the beginning, 1000 at a time. ListUsersPage page = FirebaseAuth.getInstance().listUsers(null); while (page != null) { for (ExportedUserRecord user : page.getValues()) { System.out.println("User: " + user.getUid()); } page = page.getNextPage(); } // Iterate through all users. This will still retrieve users in batches, // buffering no more than 1000 users in memory at a time. page = FirebaseAuth.getInstance().listUsers(null); for (ExportedUserRecord user : page.iterateAll()) { System.out.println("User: " + user.getUid()); } ``` -------------------------------- ### Get User by Email (Node.js) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches user data using their email address. This method is useful when the UID is not known. ```javascript getAuth() .getUserByEmail(email) .then((userRecord) => { // See the UserRecord reference doc for the contents of userRecord. console.log(`Successfully fetched user data: ${userRecord.toJSON()}`); }) .catch((error) => { console.log('Error fetching user data:', error); }); ``` -------------------------------- ### List All Users (Go) Source: https://firebase.google.com/docs/auth/admin/manage-users Provides Go code for listing users, demonstrating iteration using an iterator and paginated retrieval. Users are fetched in batches of 1000 by default. ```go // Note, behind the scenes, the Users() iterator will retrive 1000 Users at a time through the API iter := client.Users(ctx, "") for { user, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatalf("error listing users: %s\n", err) } log.Printf("read user user: %v\n", user) } // Iterating by pages 100 users at a time. // Note that using both the Next() function on an iterator and the NextPage() // on a Pager wrapping that same iterator will result in an error. pager := iterator.NewPager(client.Users(ctx, ""), 100, "") for { var users []*auth.ExportedUserRecord nextPageToken, err := pager.NextPage(&users) if err != nil { log.Fatalf("paging error %v\n", err) } for _, u := range users { log.Printf("read user user: %v\n", u) } if nextPageToken == "" { break } } ``` -------------------------------- ### Import Users with BCRYPT (Go) Source: https://firebase.google.com/docs/auth/admin/import-users This Go snippet shows how to import users with BCRYPT hashed passwords. The password hash and salt should be passed as byte slices. ```go users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("user@example.com"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.Bcrypt{} result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } ``` -------------------------------- ### Get User by UID (C#) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches user details using their UID. This method is asynchronous and requires awaiting the result. ```csharp UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}"); ``` -------------------------------- ### List All Users (C#) Source: https://firebase.google.com/docs/auth/admin/manage-users Shows how to list users asynchronously in C# using `ListUsersAsync`. It demonstrates iterating through raw responses and individual user records. ```csharp // Start listing users from the beginning, 1000 at a time. 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}"); } } // Iterate through all users. This will still retrieve users in batches, // buffering no more than 1000 users in memory at a time. var enumerator = FirebaseAuth.DefaultInstance.ListUsersAsync(null).GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { ExportedUserRecord user = enumerator.Current; Console.WriteLine($"User: {user.Uid}"); } ``` -------------------------------- ### Get User by UID (Java) Source: https://firebase.google.com/docs/auth/admin/manage-users Retrieves user information using their UID. Requires the Firebase Admin SDK to be set up. ```java UserRecord userRecord = FirebaseAuth.getInstance().getUser(uid); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getUid()); ``` -------------------------------- ### User Import Records (Go) Source: https://firebase.google.com/docs/auth/admin/import-users Construct user import records in Go, using a builder pattern for UID, email, and password hash/salt. This prepares the data for the import operation. ```go // Up to 1000 users can be imported at once. var users []*auth.UserToImport users = append(users, (&auth.UserToImport{}). UID("uid1"). Email("user1@example.com"). PasswordHash([]byte("passwordHash1")), PasswordSalt([]byte("salt1"))) users = append(users, (&auth.UserToImport{}). UID("uid2"). Email("user2@example.com"). PasswordHash([]byte("passwordHash2")), PasswordSalt([]byte("salt2"))) ``` -------------------------------- ### Import User Records (Python) Source: https://firebase.google.com/docs/auth/admin/import-users Prepare a list of user records for import, specifying UID, email, and password hash/salt. This is the initial data structure for Python imports. ```python users = [ auth.ImportUserRecord( uid='uid1', email='user1@example.com', password_hash=b'password_hash_1', password_salt=b'salt1' ), auth.ImportUserRecord( uid='uid2', email='user2@example.com', password_hash=b'password_hash_2', password_salt=b'salt2' ), ] ``` -------------------------------- ### Get User by UID (Python) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches a user's record by their UID. Make sure to import the auth module from firebase_admin. ```python from firebase_admin import auth user = auth.get_user(uid) print(f'Successfully fetched user data: {user.uid}') ``` -------------------------------- ### Get User by Phone Number (Java) Source: https://firebase.google.com/docs/auth/admin/manage-users Retrieves user information using their phone number. The phone number must be in E.164 format. ```java UserRecord userRecord = FirebaseAuth.getInstance().getUserByPhoneNumber(phoneNumber); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getPhoneNumber()); ``` -------------------------------- ### Get User by Phone Number (Node.js) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches user data using their phone number. Ensure the phone number is in E.164 format. ```javascript getAuth() .getUserByPhoneNumber(phoneNumber) .then((userRecord) => { // See the UserRecord reference doc for the contents of userRecord. console.log(`Successfully fetched user data: ${userRecord.toJSON()}`); }) .catch((error) => { console.log('Error fetching user data:', error); }); ``` -------------------------------- ### Get User by UID (Go) Source: https://firebase.google.com/docs/auth/admin/manage-users Retrieves user data using the provided UID. Ensure you have an initialized Firebase app and an auth client. ```go // Get an auth client from the firebase.App client, err := app.Auth(ctx) if err != nil { log.Fatalf("error getting Auth client: %v\n", err) } u, err := client.GetUser(ctx, uid) if err != nil { log.Fatalf("error getting user %s: %v\n", uid, err) } log.Printf("Successfully fetched user data: %v\n", u) ``` -------------------------------- ### List All Users (Python) Source: https://firebase.google.com/docs/auth/admin/manage-users Shows how to list users in Python, including iterating through pages and all users. The `list_users()` method retrieves users in batches. ```python # Start listing users from the beginning, 1000 at a time. page = auth.list_users() while page: for user in page.users: print('User: ' + user.uid) # Get next batch of users. page = page.get_next_page() # Iterate through all users. This will still retrieve users in batches, # buffering no more than 1000 users in memory at a time. for user in auth.list_users().iterate_all(): print('User: ' + user.uid) ``` -------------------------------- ### Get User Custom Claims in C# Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieves a user record by UID and accesses their custom claims, printing the 'admin' claim value. ```csharp // Lookup the user associated with the specified uid. UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine(user.CustomClaims["admin"]); ``` -------------------------------- ### Get User Custom Claims in Python Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieves a user record by UID and accesses their custom claims, printing the 'admin' claim value. ```python # Lookup the user associated with the specified uid. user = auth.get_user(uid) # The claims can be accessed on the user record. print(user.custom_claims.get('admin')) ``` -------------------------------- ### Import Users with Standard Scrypt Hashing (Java) Source: https://firebase.google.com/docs/auth/admin/import-users This Java code imports users with scrypt-hashed passwords. Password hash and salt must be converted to byte arrays. ```java try { List users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("user@example.com") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash( StandardScrypt.builder() .setMemoryCost(1024) .setParallelization(16) .setBlockSize(8) .setDerivedKeyLength(64) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } ``` -------------------------------- ### Get User Custom Claims in Java Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieves a user record by UID and accesses their custom claims, printing the 'admin' claim value. ```java // Lookup the user associated with the specified uid. UserRecord user = FirebaseAuth.getInstance().getUser(uid); System.out.println(user.getCustomClaims().get("admin")); ``` -------------------------------- ### Import Users with BCRYPT (Java) Source: https://firebase.google.com/docs/auth/admin/import-users This Java snippet demonstrates importing users with BCRYPT hashed passwords. It requires setting the password hash and salt as byte arrays. ```java try { List users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("user@example.com") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash(Bcrypt.getInstance()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } ``` -------------------------------- ### Get User Custom Claims in Node.js Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieves a user record by UID and accesses their custom claims, specifically checking for the 'admin' claim. ```javascript // Lookup the user associated with the specified uid. getAuth() .getUser(uid) .then((userRecord) => { // The claims can be accessed on the user record. console.log(userRecord.customClaims['admin']); }); ``` -------------------------------- ### Import Users with Scrypt Hash (Go) Source: https://firebase.google.com/docs/auth/admin/import-users?hl=es-419 Import users with Scrypt-hashed passwords in Go. This requires decoding base64 parameters into raw bytes for the hash configuration. ```go // Users retrieved from Firebase Auth's backend need to be base64URL decoded users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("user@example.com"). PasswordHash(b64URLdecode("password-hash")), PasswordSalt(b64URLdecode("salt")), } // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. h := hash.Scrypt{ Key: b64Stddecode("base64-secret"), SaltSeparator: b64Stddecode("base64-salt-separator"), Rounds: 8, MemoryCost: 14, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } ``` -------------------------------- ### Initialize ActionCodeSettings in Java Source: https://firebase.google.com/docs/auth/admin/email-action-links Set up ActionCodeSettings for email actions in Java, including the continue URL, mobile app handling, and platform-specific configurations for iOS and Android. Uses a dynamic link domain for custom linking. ```java ActionCodeSettings actionCodeSettings = ActionCodeSettings.builder() .setUrl("https://www.example.com/checkout?cartId=1234") .setHandleCodeInApp(true) .setIosBundleId("com.example.ios") .setAndroidPackageName("com.example.android") .setAndroidInstallApp(true) .setAndroidMinimumVersion("12") .setDynamicLinkDomain("coolapp.page.link") .build(); ``` -------------------------------- ### Get User by UID (Node.js) Source: https://firebase.google.com/docs/auth/admin/manage-users Fetches user data using their unique user ID (uid). Ensure the Firebase Admin SDK is initialized. ```javascript getAuth() .getUser(uid) .then((userRecord) => { // See the UserRecord reference doc for the contents of userRecord. console.log(`Successfully fetched user data: ${userRecord.toJSON()}`); }) .catch((error) => { console.log('Error fetching user data:', error); }); ``` -------------------------------- ### Get User Custom Claims in Go Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieves a user record by UID and accesses their custom claims, checking if the 'admin' claim exists and is true. ```go // Lookup the user associated with the specified uid. user, err := client.GetUser(ctx, uid) if err != nil { log.Fatal(err) } // The claims can be accessed on the user record. if admin, ok := user.CustomClaims["admin"]; ok { if admin.(bool) { log.Println(admin) } } auth.go ``` -------------------------------- ### Import User Records (Java) Source: https://firebase.google.com/docs/auth/admin/import-users Creates a list of user import records for Java, including UID, email, password hash, and salt. The API supports importing up to 1000 users per request. ```java // Up to 1000 users can be imported at once. List users = new ArrayList<>(); users.add(ImportUserRecord.builder() .setUid("uid1") .setEmail("user1@example.com") .setPasswordHash("passwordHash1".getBytes()) .setPasswordSalt("salt1".getBytes()) .build()); users.add(ImportUserRecord.builder() .setUid("uid2") .setEmail("user2@example.com") .setPasswordHash("passwordHash2".getBytes()) .setPasswordSalt("salt2".getBytes()) .build()); ``` -------------------------------- ### Verify Session Cookie in Node.js Source: https://firebase.google.com/docs/auth/admin/manage-cookies Verify a session cookie on a POST request to a protected route. This example checks for cookie availability and session revocation. ```javascript // Whenever a user is accessing restricted content that requires authentication. app.post('/profile', (req, res) => { const sessionCookie = req.cookies.session || ''; // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. getAuth() .verifySessionCookie(sessionCookie, true /** checkRevoked */) .then((decodedClaims) => { serveContentForUser('/profile', req, res, decodedClaims); }) .catch((error) => { // Session cookie is unavailable or invalid. Force user to login. res.redirect('/login'); }); }); ``` -------------------------------- ### Initialize ActionCodeSettings in Python Source: https://firebase.google.com/docs/auth/admin/email-action-links Create an ActionCodeSettings object in Python for email actions. This configuration specifies the continue URL, enables in-app handling, and sets details for iOS and Android, including a dynamic link domain. ```python action_code_settings = auth.ActionCodeSettings( url='https://www.example.com/checkout?cartId=1234', handle_code_in_app=True, ios_bundle_id='com.example.ios', android_package_name='com.example.android', android_install_app=True, android_minimum_version='12', dynamic_link_domain='coolapp.page.link', ) ``` -------------------------------- ### Reauthenticate User on Client After Token Revocation (JavaScript) Source: https://firebase.google.com/docs/auth/admin/manage-sessions When a token is revoked, prompt the user for reauthentication. This example shows reauthentication for an email/password user using `reauthenticateWithCredential`. ```javascript function onIdTokenRevocation() { // For an email/password user. Prompt the user for the password again. let password = prompt('Please provide your password for reauthentication'); let credential = firebase.auth.EmailAuthProvider.credential( firebase.auth().currentUser.email, password); firebase.auth().currentUser.reauthenticateWithCredential(credential) .then(result => { // User successfully reauthenticated. New ID tokens should be valid. }) .catch(error => { // An error occurred. }); } ``` -------------------------------- ### Import Users with BCRYPT (C#) Source: https://firebase.google.com/docs/auth/admin/import-users Use this C# snippet to import users with BCRYPT hashed passwords. Password hash and salt are provided as byte arrays. ```csharp try { var users = new List() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Bcrypt(), }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } ``` -------------------------------- ### Import Users with PBKDF2_SHA256 Hashing (C#) Source: https://firebase.google.com/docs/auth/admin/import-users C# code for importing users with PBKDF2_SHA256 hashed passwords. The password hash and salt are provided as byte arrays. Ensure the correct number of hashing rounds is configured. ```csharp try { var users = new List() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Pbkdf2Sha256() { Rounds = 100000, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } ``` -------------------------------- ### Set Custom Claims for a User (Go) Source: https://firebase.google.com/docs/auth/admin/custom-claims Sets initial custom claims for a user after verifying their email. This is useful for granting specific privileges. ```go user, err := client.GetUserByEmail(ctx, "user@admin.example.com") if err != nil { log.Fatal(err) } // Confirm user is verified if user.EmailVerified { // Add custom claims for additional privileges. // This will be picked up by the user on token refresh or next sign in on new device. err := client.SetCustomUserClaims(ctx, user.UID, map[string]interface{}{"admin": true}) if err != nil { log.Fatalf("error setting custom claims %v\n", err) } } ``` -------------------------------- ### Import Users with Standard Scrypt Hashing (Node.js) Source: https://firebase.google.com/docs/auth/admin/import-users Use this snippet to import users with scrypt-hashed passwords in Node.js. Ensure passwordHash and passwordSalt are provided as byte buffers. ```javascript getAuth() .importUsers( [ { uid: 'some-uid', email: 'user@example.com', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('salt'), }, ], { hash: { algorithm: 'STANDARD_SCRYPT', memoryCost: 1024, parallelization: 16, blockSize: 8, derivedKeyLength: 64, }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); ``` -------------------------------- ### Import Users with PBKDF2_SHA256 Hashing (Node.js) Source: https://firebase.google.com/docs/auth/admin/import-users Use this snippet to import users with passwords hashed using PBKDF2_SHA256. Ensure the password hash and salt are provided as byte buffers. The number of rounds for hashing must be specified. ```javascript getAuth() .importUsers( [ { uid: 'some-uid', email: 'user@example.com', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('salt'), }, ], { hash: { algorithm: 'PBKDF2_SHA256', rounds: 100000, }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); ``` -------------------------------- ### Cloud Storage Rules for Custom Token User Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Example Cloud Storage rules to restrict access based on the authenticated user's UID, which is derived from the custom token. ```json service firebase.storage { match /b//o { match /adminContent/{filename} { allow read, write: if request.auth != null && request.auth.uid == "some-uid"; } } } ``` -------------------------------- ### Import Users with BCRYPT (Python) Source: https://firebase.google.com/docs/auth/admin/import-users Import users with BCRYPT hashed passwords using this Python snippet. Ensure the password hash and salt are provided as byte strings. ```python users = [ auth.ImportUserRecord( uid='some-uid', email='user@example.com', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.bcrypt() try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) ``` -------------------------------- ### Realtime Database Rules for Custom Token User Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Example Realtime Database rules to restrict access based on the authenticated user's UID, which is derived from the custom token. ```json { "rules": { "adminContent": { ".read": "auth.uid === 'some-uid'" } } } ``` -------------------------------- ### Get Custom Claims from ID Token (JavaScript) Source: https://firebase.google.com/docs/auth/admin/custom-claims Retrieve custom claims from a user's ID token to conditionally display UI elements. Ensure the user is authenticated before calling. ```javascript import { getAuth } from "firebase/auth"; getAuth().currentUser?.getIdTokenResult() .then((idTokenResult) => { // Confirm the user is an Admin. if (!!idTokenResult.claims.admin) { // Show admin UI. showAdminUI(); } else { // Show regular user UI. showRegularUI(); } }) .catch((error) => { console.log(error); }); ``` -------------------------------- ### Initialize ActionCodeSettings in C# Source: https://firebase.google.com/docs/auth/admin/email-action-links Define ActionCodeSettings in C# for email action links, specifying the continue URL, enabling in-app handling, and setting iOS and Android configurations. Includes a link domain for custom routing. ```csharp 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", }; ``` -------------------------------- ### Create Custom Token in PHP Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens Use the `firebase/php-jwt` library to create a custom token. Ensure you have the service account email and private key, and that the JWT library is installed via Composer. ```php // Requires: composer require firebase/php-jwt use Firebase\JWT\JWT; // Get your service account's email address and private key from the JSON key file $service_account_email = "abc-123@a-b-c-123.iam.gserviceaccount.com"; $private_key = "-----BEGIN PRIVATE KEY-----..."; function create_custom_token($uid, $is_premium_account) { global $service_account_email, $private_key; $now_seconds = time(); $payload = array( "iss" => $service_account_email, "sub" => $service_account_email, "aud" => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit", "iat" => $now_seconds, "exp" => $now_seconds+(60*60), // Maximum expiration time is one hour "uid" => $uid, "claims" => array( "premium_account" => $is_premium_account ) ); return JWT::encode($payload, $private_key, "RS256"); } ``` -------------------------------- ### Import Users with Scrypt Hash (Python) Source: https://firebase.google.com/docs/auth/admin/import-users?hl=es-419 Use this snippet to import users with passwords hashed using the Scrypt algorithm. Ensure base64 encoded parameters are decoded into raw bytes. ```python hash_alg = auth.UserImportHash.scrypt( key=base64.b64decode('base64_secret'), salt_separator=base64.b64decode('base64_salt_separator'), rounds=8, memory_cost=14 ) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) ```