支援 CORS 的 HTTP 驗證
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
支援含憑證的 CORS 要求的 HTTP 函式。
程式碼範例
Java
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Node.js
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Ruby
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。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 configure HTTP functions to support Cross-Origin Resource Sharing (CORS) requests with credentials.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples show how to set CORS headers for both preflight requests (using the \u003ccode\u003eOPTIONS\u003c/code\u003e method) and main requests.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication to Cloud Run functions requires setting up Application Default Credentials.\u003c/p\u003e\n"],["\u003cp\u003eCORS headers, such as \u003ccode\u003eAccess-Control-Allow-Origin\u003c/code\u003e, \u003ccode\u003eAccess-Control-Allow-Credentials\u003c/code\u003e, \u003ccode\u003eAccess-Control-Allow-Methods\u003c/code\u003e, and \u003ccode\u003eAccess-Control-Allow-Headers\u003c/code\u003e are configured to manage cross-origin access.\u003c/p\u003e\n"],["\u003cp\u003eThe samples are provided for Go, Java, Node.js, Python, and Ruby, illustrating the implementation in each of these languages.\u003c/p\u003e\n"]]],[],null,["# HTTP Auth with CORS\n\nHTTP function that supports CORS requests with credentials.\n\nCode sample\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 http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n // CORSEnabledFunctionAuth is an example of setting CORS headers with\n // authentication enabled.\n // For more information about CORS and CORS preflight requests, see\n // https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.\n func CORSEnabledFunctionAuth(w http.ResponseWriter, r *http.Request) {\n \t// Set CORS headers for the preflight request\n \tif r.Method == http.MethodOptions {\n \t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n \t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization\")\n \t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n \t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"https://example.com\")\n \t\tw.Header().Set(\"Access-Control-Max-Age\", \"3600\")\n \t\tw.WriteHeader(http.StatusNoContent)\n \t\treturn\n \t}\n \t// Set CORS headers for the main request.\n \tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n \tw.Header().Set(\"Access-Control-Allow-Origin\", \"https://example.com\")\n \tfmt.Fprint(w, \"Hello World!\")\n }\n\n func init() {\n \tfunctions.HTTP(\"CORSEnabledFunctionAuth\", CORSEnabledFunctionAuth)\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\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.BufferedWriter;\n import java.io.IOException;\n import java.net.HttpURLConnection;\n\n public class CorsEnabledAuth implements HttpFunction {\n // corsEnabledAuth is an example of setting CORS headers.\n // For more information about CORS and CORS preflight requests, see\n // https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n // Set CORS headers\n // Allows GETs from origin https://mydomain.com\n // with the Authorization header present\n response.appendHeader(\"Access-Control-Allow-Origin\", \"https://mydomain.com\");\n response.appendHeader(\"Access-Control-Allow-Credentials\", \"true\");\n\n if (\"OPTIONS\".equals(request.getMethod())) {\n response.appendHeader(\"Access-Control-Allow-Methods\", \"GET\");\n response.appendHeader(\"Access-Control-Allow-Headers\", \"Authorization\");\n response.appendHeader(\"Access-Control-Max-Age\", \"3600\");\n response.setStatusCode(HttpURLConnection.HTTP_NO_CONTENT);\n return;\n }\n\n // Handle the main request\n BufferedWriter writer = response.getWriter();\n writer.write(\"CORS headers set successfully!\");\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 const functions = require('@google-cloud/functions-framework');\n\n /**\n * HTTP function that supports CORS requests with credentials.\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('corsEnabledFunctionAuth', (req, res) =\u003e {\n // Set CORS headers for preflight requests\n // Allows GETs from origin https://mydomain.com with Authorization header\n\n res.set('Access-Control-Allow-Origin', 'https://mydomain.com');\n res.set('Access-Control-Allow-Credentials', 'true');\n\n if (req.method === 'OPTIONS') {\n // Send response to OPTIONS requests\n res.set('Access-Control-Allow-Methods', 'GET');\n res.set('Access-Control-Allow-Headers', 'Authorization');\n res.set('Access-Control-Max-Age', '3600');\n res.status(204).send('');\n } else {\n res.send('Hello World!');\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 functions_framework\n\n @functions_framework.http\n def cors_enabled_function_auth(request):\n # For more information about CORS and CORS preflight requests, see\n # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request\n # for more information.\n\n # Set CORS headers for preflight requests\n if request.method == \"OPTIONS\":\n # Allows GET requests from origin https://mydomain.com with\n # Authorization header\n headers = {\n \"Access-Control-Allow-Origin\": \"https://mydomain.com\",\n \"Access-Control-Allow-Methods\": \"GET\",\n \"Access-Control-Allow-Headers\": \"Authorization\",\n \"Access-Control-Max-Age\": \"3600\",\n \"Access-Control-Allow-Credentials\": \"true\",\n }\n return (\"\", 204, headers)\n\n # Set CORS headers for main requests\n headers = {\n \"Access-Control-Allow-Origin\": \"https://mydomain.com\",\n \"Access-Control-Allow-Credentials\": \"true\",\n }\n\n return (\"Hello World!\", 200, headers)\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 FunctionsFramework.http \"cors_enabled_function_auth\" do |request|\n # For more information about CORS and CORS preflight requests, see\n # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request\n # for more information.\n\n # Set CORS headers for preflight requests\n if request.options?\n # Allows GET requests from origin https://mydomain.com with\n # Authorization header\n headers = {\n \"Access-Control-Allow-Origin\" =\u003e \"https://mydomain.com\",\n \"Access-Control-Allow-Methods\" =\u003e \"GET\",\n \"Access-Control-Allow-Headers\" =\u003e \"Authorization\",\n \"Access-Control-Max-Age\" =\u003e \"3600\",\n \"Access-Control-Allow-Credentials\" =\u003e \"true\"\n }\n [204, headers, []]\n else\n # Set CORS headers for main requests\n headers = {\n \"Access-Control-Allow-Origin\" =\u003e \"https://mydomain.com\",\n \"Access-Control-Allow-Credentials\" =\u003e \"true\"\n }\n\n [200, headers, [\"Hello World!\"]]\n end\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)."]]