Firebase Auth
bookmark_borderbookmark
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在 Firebase Auth 用户对象发生变化时触发函数。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","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)."]]