CORS로 HTTP 인증

사용자 인증 정보가 있는 CORS 요청을 지원하는 HTTP 함수

코드 샘플

Go

Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


// Package http provides a set of HTTP Cloud Functions samples.
package http

import (
	"fmt"
	"net/http"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

// CORSEnabledFunctionAuth is an example of setting CORS headers with
// authentication enabled.
// For more information about CORS and CORS preflight requests, see
// https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.
func CORSEnabledFunctionAuth(w http.ResponseWriter, r *http.Request) {
	// Set CORS headers for the preflight request
	if r.Method == http.MethodOptions {
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Allow-Headers", "Authorization")
		w.Header().Set("Access-Control-Allow-Methods", "POST")
		w.Header().Set("Access-Control-Allow-Origin", "https://example.com")
		w.Header().Set("Access-Control-Max-Age", "3600")
		w.WriteHeader(http.StatusNoContent)
		return
	}
	// Set CORS headers for the main request.
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Allow-Origin", "https://example.com")
	fmt.Fprint(w, "Hello World!")
}

func init() {
	functions.HTTP("CORSEnabledFunctionAuth", CORSEnabledFunctionAuth)
}

Java

Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.HttpURLConnection;

public class CorsEnabledAuth implements HttpFunction {
  // corsEnabledAuth is an example of setting CORS headers.
  // For more information about CORS and CORS preflight requests, see
  // https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    // Set CORS headers
    //   Allows GETs from origin https://mydomain.com
    //   with the Authorization header present
    response.appendHeader("Access-Control-Allow-Origin", "https://mydomain.com");
    response.appendHeader("Access-Control-Allow-Credentials", "true");

    if ("OPTIONS".equals(request.getMethod())) {
      response.appendHeader("Access-Control-Allow-Methods", "GET");
      response.appendHeader("Access-Control-Allow-Headers", "Authorization");
      response.appendHeader("Access-Control-Max-Age", "3600");
      response.setStatusCode(HttpURLConnection.HTTP_NO_CONTENT);
      return;
    }

    // Handle the main request
    BufferedWriter writer = response.getWriter();
    writer.write("CORS headers set successfully!");
  }
}

Node.js

Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const functions = require('@google-cloud/functions-framework');

/**
 * HTTP function that supports CORS requests with credentials.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
functions.http('corsEnabledFunctionAuth', (req, res) => {
  // Set CORS headers for preflight requests
  // Allows GETs from origin https://mydomain.com with Authorization header

  res.set('Access-Control-Allow-Origin', 'https://mydomain.com');
  res.set('Access-Control-Allow-Credentials', 'true');

  if (req.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    res.set('Access-Control-Allow-Methods', 'GET');
    res.set('Access-Control-Allow-Headers', 'Authorization');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
  } else {
    res.send('Hello World!');
  }
});

Python

Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import functions_framework

@functions_framework.http
def cors_enabled_function_auth(request):
    # For more information about CORS and CORS preflight requests, see
    # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
    # for more information.

    # Set CORS headers for preflight requests
    if request.method == "OPTIONS":
        # Allows GET requests from origin https://mydomain.com with
        # Authorization header
        headers = {
            "Access-Control-Allow-Origin": "https://mydomain.com",
            "Access-Control-Allow-Methods": "GET",
            "Access-Control-Allow-Headers": "Authorization",
            "Access-Control-Max-Age": "3600",
            "Access-Control-Allow-Credentials": "true",
        }
        return ("", 204, headers)

    # Set CORS headers for main requests
    headers = {
        "Access-Control-Allow-Origin": "https://mydomain.com",
        "Access-Control-Allow-Credentials": "true",
    }

    return ("Hello World!", 200, headers)

Ruby

Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

FunctionsFramework.http "cors_enabled_function_auth" do |request|
  # For more information about CORS and CORS preflight requests, see
  # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
  # for more information.

  # Set CORS headers for preflight requests
  if request.options?
    # Allows GET requests from origin https://mydomain.com with
    # Authorization header
    headers = {
      "Access-Control-Allow-Origin"      => "https://mydomain.com",
      "Access-Control-Allow-Methods"     => "GET",
      "Access-Control-Allow-Headers"     => "Authorization",
      "Access-Control-Max-Age"           => "3600",
      "Access-Control-Allow-Credentials" => "true"
    }
    [204, headers, []]
  else
    # Set CORS headers for main requests
    headers = {
      "Access-Control-Allow-Origin"      => "https://mydomain.com",
      "Access-Control-Allow-Credentials" => "true"
    }

    [200, headers, ["Hello World!"]]
  end
end

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.