HTTP Auth with CORS
Stay organized with collections
Save and categorize content based on your preferences.
HTTP function that supports CORS requests with credentials.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","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)."]]