이 페이지에서는 Cloud Endpoints에서 사용자 인증을 지원하는 방법을 설명합니다.
사용자를 인증하려면 클라이언트 애플리케이션이 HTTP 요청의 승인 헤더에 있는 JSON 웹 토큰(JWT)을 백엔드 API로 전송해야 합니다. Extensible Service Proxy(ESP)는 API를 대신하여 토큰의 유효성을 검사하므로 인증을 처리하기 위해 API에 코드를 추가할 필요가 없습니다. 하지만 선택한 인증 방법을 지원하도록 OpenAPI 문서를 구성해야 합니다.
ESP는 JWT 발급자의 공개 키를 사용하여 JWT의 성능을 검사합니다. ESP는 5분 동안 공개 키를 캐시합니다. 또한 ESP는 검사된 JWT를 5분 동안 또는 JWT 만료까지 중 먼저 발생하는 시점까지 캐시합니다.
시작하기 전에
사용자가 Google 계정으로 로그인하여 인증할 수 있도록 인증 코드를 클라이언트 애플리케이션에 추가합니다.
클라이언트 애플리케이션이 HTTP 요청을 전송할 때 요청의 승인 헤더에는 다음 JWT 클레임이 포함되어야 합니다.
보안 섹션을 API 수준에서 추가하여 전체 API에 적용하거나 메소드 수준에서 추가하여 특정 메소드에 적용합니다.
security:
- google_id_token: []
OpenAPI 문서에 여러 보안 정의를 정의할 수 있지만 정의마다 발급자가 달라야 합니다. API 및 메서드 수준 모두에 security 섹션을 사용하는 경우에는 메서드 수준 설정이 API 수준 설정을 재정의합니다.
x-google-audiences 필드는 필수가 아닙니다. ESP는 aud 클레임에 https://SERVICE_NAME 형식의 백엔드 서비스 이름이 포함된 모든 JWT를 수락합니다. 백엔드 서비스에 액세스하도록 추가 클라이언트 ID를 허용하려면 허용된 클라이언트 ID를 쉼표로 구분된 값을 사용하여 x-google-audiences 필드에 입력합니다. 그러면 ESP가 aud 클레임에서 지정된 클라이언트 ID가 있는 JWT를 수락합니다.
x-google-extensions를 추가하여 JWT 위치를 맞춤설정할 수도 있습니다. 자세한 내용은 openAPI 확장 프로그램을 참조하세요.
Endpoints API에 인증된 호출 실행
인증 토큰을 사용하여 요청을 전송할 경우 보안상의 이유로 Authorization:Bearer 헤더에 인증 토큰을 포함하는 것이 좋습니다. 예를 들면 다음과 같습니다.
ESP는 수신하는 모든 헤더를 전달합니다. 하지만 OpenAPI 사양의 x-google-backend 또는 gRPC 서비스 구성의 BackendRule에서 백엔드 주소를 지정할 때 ESP는 원래 Authorization 헤더를 재정의합니다.
ESP는 X-Endpoint-API-UserInfo의 인증 결과를 백엔드 API에 전송합니다. 원래 Authorization 헤더 대신 이 헤더를 사용하는 것이 좋습니다. 이 헤더는 base64url이 JSON 객체를 인코딩하는 문자열입니다. JSON 객체 형식은 ESPv2와 ESP 간에 다릅니다.
ESPv2의 경우 JSON 객체는 정확히 원래 JWT 페이로드입니다. ESP의 경우 JSON 객체는 서로 다른 필드 이름을 사용하고 원래 JWT 페이로드를 claims 필드에 넣습니다.
형식에 대한 자세한 내용은 백엔드 서비스에서 JWT 처리를 참조하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eClient applications must include a JSON Web Token (JWT) in the authorization header of HTTP requests for user authentication in Cloud Endpoints, which is then validated by the Extensible Service Proxy (ESP).\u003c/p\u003e\n"],["\u003cp\u003eThe OpenAPI document requires a security requirement object and a security definitions object to enable ESP to validate the claims within the signed JWT for user authentication.\u003c/p\u003e\n"],["\u003cp\u003eTo support authentication via a Google ID token, the OpenAPI document's security definition should be configured with specific fields such as \u003ccode\u003ex-google-issuer\u003c/code\u003e, \u003ccode\u003ex-google-jwks_uri\u003c/code\u003e, and \u003ccode\u003ex-google-audiences\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eWhile the \u003ccode\u003eAuthorization: Bearer\u003c/code\u003e header is the recommended method for sending authentication tokens, tokens can also be included in a query parameter named \u003ccode\u003eaccess_token\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eESP forwards authentication results to the backend API using the \u003ccode\u003eX-Endpoint-API-UserInfo\u003c/code\u003e header, which contains a \u003ccode\u003ebase64url\u003c/code\u003e encoded JSON object with different formats between ESPv2 and ESP, and should be used instead of the original \u003ccode\u003eAuthorization\u003c/code\u003e header.\u003c/p\u003e\n"]]],[],null,["# Using Google ID tokens to authenticate users\n\nOpenAPI \\| gRPC\n\n\u003cbr /\u003e\n\nThis page describes how to support user authentication in Cloud Endpoints.\n\nTo authenticate a user, a client application must send a\n[JSON Web Token (JWT)](https://jwt.io/) in the authorization header of the\nHTTP request to your backend API. The\n[Extensible Service Proxy (ESP)](/endpoints/docs/glossary#extensible_service_proxy)\nvalidates the token on behalf of your API, so you don't have to add any code in\nyour API to process the authentication. However, you do need to configure your\nOpenAPI document to support your chosen authentication methods.\n\nESP validates a JWT in a performant way by using the JWT's\nissuer's public keys. ESP caches the public keys for five\nminutes. In addition, ESP caches validated JWTs for five minutes\nor until JWT expiry, whichever happens first.\n\nBefore you begin\n----------------\n\n- Add authentication code to your client application that allows users to authenticate by signing in with Google account.\n\n\n- When your client application sends an HTTP request, the authorization header in the request must contain the following JWT claims:\n - `iss` (issuer)\n - `sub` (subject)\n - `aud` (audience)\n - `iat` (issued at)\n - `exp` (expiration time)\n\n\u003cbr /\u003e\n\nConfiguring ESP to support client authentication\n------------------------------------------------\n\n\nYou must have a [security\nrequirement object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject) and a [security\ndefinitions object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityDefinitionsObject) in your OpenAPI document for ESP to\nvalidate the claims in the signed JWT.\n\n\u003cbr /\u003e\n\nTo support authentication using a Google ID token:\n\n1. Add the following to the security definition in your OpenAPI\n document:\n\n securityDefinitions:\n google_id_token:\n authorizationUrl: \"\"\n flow: \"implicit\"\n type: \"oauth2\"\n x-google-issuer: \"https://accounts.google.com\"\n x-google-jwks_uri: \"https://www.googleapis.com/oauth2/v3/certs\"\n # Optional. Replace YOUR-CLIENT-ID with your client ID\n x-google-audiences: \"YOUR-CLIENT-ID\"\n\n2. Add a security section at either the API level to apply to the entire\n API, or at the method level to apply to a specific method.\n\n security:\n - google_id_token: []\n\n\nYou can define multiple security definitions in the OpenAPI document, but each\ndefinition must have a different issuer. If you use security sections at both\nthe API level and at the method level, the method-level settings override the\nAPI-level settings.\n\n\u003cbr /\u003e\n\n\nThe `x-google-audiences` field isn't required. ESP\naccepts all JWTs with the backend service name in the form of\n`https://`\u003cvar translate=\"no\"\u003eSERVICE_NAME\u003c/var\u003e in the `aud` claim. To\nallow additional client IDs to access the backend service, you can specify the\nallowed client IDs in the `x-google-audiences` field by using\ncomma-separated values. ESP then accepts the JWTs with any of the\nspecified client IDs in the `aud` claim.\n\n\u003cbr /\u003e\n\n\nYou may also customize JWT locations by adding `x-google-extensions`. For details, see [openAPI extensions](/endpoints/docs/openapi/openapi-extensions#x-google-jwt-locations).\n\n\u003cbr /\u003e\n\nMaking an authenticated call to an Endpoints API\n------------------------------------------------\n\nWhen you send a request using an authentication token, for security reasons, we\nrecommend that you put the token in the `Authorization:Bearer` header. For\nexample: \n\n curl -H \"Authorization: Bearer ${TOKEN}\" \"${ENDPOINTS_HOST}/echo\"\n\nHere, `ENDPOINTS_HOST` and `TOKEN` are environment variables containing your\nAPI host name and authentication token, respectively. See\n[Making an authenticated request to an Endpoints API](/endpoints/docs/openapi/service-account-authentication#making_an_authenticated_request).\nfor sample code that sends a request using the `Authorization:Bearer` header.\n\nIf you cannot use the header when sending the request, you can put the\nauthentication token in a query parameter called `access_token`. For example: \n\n curl \"${ENDPOINTS_HOST}/echo?access_token=${TOKEN}\"\n\nReceiving auth results in your API\n----------------------------------\n\n\nESP usually forwards all headers it receives. However, it overrides the\noriginal `Authorization` header when the backend address is specified by\n`x-google-backend` in OpenAPI specification or `BackendRule`\nin gRPC service configuration.\n\n\nESP will send the authentication result in the `X-Endpoint-API-UserInfo`\nto the backend API. We recommend using this header instead of the original\n`Authorization` header. This header is a string that `base64url` encodes\na JSON object. The JSON object format differs between ESPv2 and ESP.\nFor ESPv2, the JSON object is exactly the original JWT payload. For ESP,\nthe JSON object uses different field names and put original JWT payload under `claims` field.\nSee [Handle JWTs in the backend service](/endpoints/docs/openapi/migrate-to-esp-v2#handle-jwt)\nfor more information on the format.\n\n\u003cbr /\u003e\n\nWhat's next\n-----------\n\n\n- [Troubleshooting JWT validation](/endpoints/docs/openapi/troubleshoot-jwt)\n- [Authentication between services](/endpoints/docs/openapi/service-account-authentication)\n\n\u003cbr /\u003e"]]