Firebase Auth
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Déclenchez une fonction lorsqu'un objet utilisateur Firebase Auth est modifié.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates how to trigger a function in response to changes in a Firebase Auth user object.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code samples showcase implementations in C#, Go, Java, Node.js, PHP, Python, and Ruby for handling Firebase Auth user events.\u003c/p\u003e\n"],["\u003cp\u003eThe function trigger is able to extract and log information such as user UID, creation time, and email from the Firebase Auth event.\u003c/p\u003e\n"],["\u003cp\u003eTo authenticate to Cloud Run functions, it is important to set up Application Default Credentials as specified in the "Set up authentication for a local development environment" document.\u003c/p\u003e\n"]]],[],null,["# Firebase Auth\n\nTriggers a function when a Firebase Auth user object changes.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Firebase Authentication Triggers](/functions/1stgendocs/calling/firebase-auth)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using CloudNative.CloudEvents;\n using Google.Cloud.Functions.Framework;\n using Google.Events.Protobuf.Firebase.Auth.V1;\n using Microsoft.Extensions.Logging;\n using System.Threading;\n using System.Threading.Tasks;\n\n namespace FirebaseAuth;\n\n public class Function : ICloudEventFunction\u003cAuthEventData\u003e\n {\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, AuthEventData data, CancellationToken cancellationToken)\n {\n _logger.LogInformation(\"Function triggered by change to user: {uid}\", data.Uid);\n if (data.Metadata is UserMetadata metadata)\n {\n _logger.LogInformation(\"User created at: {created:s}\", metadata.CreateTime.ToDateTimeOffset());\n }\n if (!string.IsNullOrEmpty(data.Email))\n {\n _logger.LogInformation(\"Email: {email}\", data.Email);\n }\n\n // In this example, we don't need to perform any asynchronous operations, so the\n // method doesn't need to be declared async.\n return Task.CompletedTask;\n }\n }\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package firebase contains a Firestore Cloud Function.\n package firebase\n\n import (\n \t\"context\"\n \t\"log\"\n \t\"time\"\n )\n\n // AuthEvent is the payload of a Firestore Auth event.\n type AuthEvent struct {\n \tEmail string `json:\"email\"`\n \tMetadata struct {\n \t\tCreatedAt time.Time `json:\"createdAt\"`\n \t} `json:\"metadata\"`\n \tUID string `json:\"uid\"`\n }\n\n // HelloAuth is triggered by Firestore Auth events.\n func HelloAuth(ctx context.Context, e AuthEvent) error {\n \tlog.Printf(\"Function triggered by creation or deletion of user: %q\", e.UID)\n \tlog.Printf(\"Created at: %v\", e.Metadata.CreatedAt)\n \tif e.Email != \"\" {\n \t\tlog.Printf(\"Email: %q\", e.Email)\n \t}\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.Context;\n import com.google.cloud.functions.RawBackgroundFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonObject;\n import java.util.logging.Logger;\n\n public class FirebaseAuth implements RawBackgroundFunction {\n private static final Logger logger = Logger.getLogger(FirebaseAuth.class.getName());\n\n // Use GSON (https://github.com/google/gson) to parse JSON content.\n private static final Gson gson = new Gson();\n\n @Override\n public void accept(String json, Context context) {\n JsonObject body = gson.fromJson(json, JsonObject.class);\n\n if (body != null && body.has(\"uid\")) {\n logger.info(\"Function triggered by change to user: \" + body.get(\"uid\").getAsString());\n }\n\n if (body != null && body.has(\"metadata\")) {\n JsonObject metadata = body.get(\"metadata\").getAsJsonObject();\n logger.info(\"Created at: \" + metadata.get(\"createdAt\").getAsString());\n }\n\n if (body != null && body.has(\"email\")) {\n logger.info(\"Email: \" + body.get(\"email\").getAsString());\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Background Function triggered by a change to a Firebase Auth user object.\n *\n * @param {!Object} event The Cloud Functions event.\n */\n exports.helloAuth = event =\u003e {\n try {\n console.log(`Function triggered by change to user: ${event.uid}`);\n console.log(`Created at: ${event.metadata.createdAt}`);\n\n if (event.email) {\n console.log(`Email: ${event.email}`);\n }\n } catch (err) {\n console.error(err);\n }\n };\n\n### PHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use Google\\CloudFunctions\\CloudEvent;\n\n function firebaseAuth(CloudEvent $cloudevent)\n {\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n $data = $cloudevent-\u003egetData();\n\n fwrite(\n $log,\n 'Function triggered by change to user: ' . $data['uid'] . PHP_EOL\n );\n fwrite($log, 'Created at: ' . $data['metadata']['createTime'] . PHP_EOL);\n\n if (isset($data['email'])) {\n fwrite($log, 'Email: ' . $data['email'] . PHP_EOL);\n }\n }\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import json\n\n def hello_auth(data, context):\n \"\"\"Triggered by creation or deletion of a Firebase Auth user object.\n Args:\n data (dict): The event payload.\n context (google.cloud.functions.Context): Metadata for the event.\n \"\"\"\n print(\"Function triggered by creation/deletion of user: %s\" % data[\"uid\"])\n print(\"Created at: %s\" % data[\"metadata\"][\"createdAt\"])\n\n if \"email\" in data:\n print(\"Email: %s\" % data[\"email\"])\n\n### Ruby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n\n # Triggered by creation or deletion of a Firebase Auth user object.\n FunctionsFramework.cloud_event \"hello_auth\" do |event|\n # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n # The Firebase event payload can be obtained from the `data` field.\n payload = event.data\n\n logger.info \"Function triggered by creation/deletion of user: #{payload['uid']}\"\n logger.info \"Created at: #{payload['metadata']['createdAt']}\"\n logger.info \"Email: #{payload['email']}\" if payload.key? \"email\"\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]