프로그래매틱 인증

이 페이지에서는 사용자 계정 또는 서비스 계정에서 IAP(Identity-Aware Proxy) 보안 리소스를 인증하는 방법을 설명합니다.

프로그래매틱 액세스는 브라우저 이외의 클라이언트에서 IAP 보호 애플리케이션을 호출하는 시나리오입니다. 여기에는 명령줄 도구, 서비스 호출 간 서비스, 모바일 애플리케이션이 포함됩니다. 사용 사례에 따라 사용자 인증 정보 또는 서비스 사용자 인증 정보를 사용하여 IAP에 인증할 수 있습니다.

  • 사용자 계정은 개별 사용자에 속합니다. 애플리케이션에서 사용자를 대신하여 IAP 보안 리소스에 액세스해야 하는 경우 사용자 계정을 인증합니다. 자세한 내용은 사용자 계정을 참고하세요.

  • 서비스 계정은 개별 사용자 대신 애플리케이션을 나타냅니다. 애플리케이션이 IAP 보안 리소스에 액세스하도록 허용하려는 경우 서비스 계정을 인증합니다. 자세한 내용은 서비스 계정을 참고하세요.

IAP는 프로그래매틱 액세스를 위해 다음과 같은 유형의 사용자 인증 정보를 지원합니다.

  • OAuth 2.0 ID 토큰: 대상 클레임이 IAP 애플리케이션의 리소스 ID로 설정된 인간 사용자 또는 서비스 계정에 대해 Google에서 발급한 토큰입니다.
  • 서비스 계정 서명 JWT: 서비스 계정의 자체 서명 또는 Google에서 발급한 JWT 토큰입니다.

Authorization 또는 Proxy-Authorization HTTP 헤더에서 이러한 사용자 인증 정보를 IAP에 전달합니다.

시작하기 전에

시작하기 전에 개발자 계정, 서비스 계정 또는 모바일 앱 사용자 인증 정보를 사용하여 프로그래매틱 방식으로 연결하려는 IAP 보안 애플리케이션이 필요합니다.

사용자 계정 인증

데스크톱 또는 모바일 앱에서 사용자가 앱에 액세스하여 프로그램이 IAP 보안 리소스와 상호작용하도록 할 수 있습니다.

모바일 앱에서 인증

  1. 모바일 앱에 OAuth 2.0 클라이언트 ID를 만들거나 기존 ID를 사용합니다. 기존 OAuth 2.0 클라이언트 ID를 사용하려면 OAuth 클라이언트를 공유하는 방법의 단계를 따릅니다. 애플리케이션의 프로그래매틱 액세스 허용 목록에 OAuth 클라이언트 ID를 추가합니다.
  2. IAP 보안 클라이언트 ID에 대한 ID 토큰을 가져옵니다.
  3. IAP 보안 리소스에 인증된 요청을 하려면 Authorization: Bearer 헤더에 ID 토큰을 포함합니다.

데스크톱 앱에서 인증

이 섹션에서는 데스크톱 명령줄에서 사용자 계정을 인증하는 방법을 설명합니다.

  1. 개발자가 명령줄에서 애플리케이션에 액세스하도록 허용하려면 데스크톱 OAuth 2.0 클라이언트 ID를 만들거나 기존 데스크톱 OAuth 클라이언트 ID를 공유합니다.
  2. 애플리케이션의 프로그래매틱 액세스 허용 목록에 OAuth ID를 추가합니다.

애플리케이션에 로그인

IAP 보안 앱에 액세스하려는 각 개발자는 먼저 로그인해야 합니다. gcloud CLI 등을 사용하여 프로세스를 스크립트로 패키징할 수 있습니다. 다음 예에서는 curl을 사용하여 로그인하고 애플리케이션에 액세스하는 데 사용할 수 있는 토큰을 생성합니다.

  1. Google Cloud 리소스에 액세스할 수 있는 계정에 로그인합니다.
  2. 수신 요청을 에코할 수 있는 로컬 서버를 시작합니다.

      # Example using Netcat (http://netcat.sourceforge.net/)
      nc -k -l 4444
    
  3. 다음 URI로 이동합니다. 여기서 DESKTOP_CLIENT_ID데스크톱 앱 클라이언트 ID입니다.

      https://accounts.google.com/o/oauth2/v2/auth?client_id=DESKTOP_CLIENT_ID&response_type=code&scope=openid%20email&access_type=offline&redirect_uri=http://localhost:4444&cred_ref=true
    
  4. 로컬 서버 출력에서 요청 매개변수를 찾습니다.

      GET /?code=CODE&scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email&hd=google.com&prompt=consent HTTP/1.1
    
  5. 다음 명령어에서 AUTH_CODE를 대체할 CODE 값을 데스크톱 앱 클라이언트 ID 및 보안 비밀과 함께 복사합니다.

      curl --verbose \
        --data client_id=DESKTOP_CLIENT_ID \
        --data client_secret=DESKTOP_CLIENT_SECRET \
        --data code=CODE \
        --data redirect_uri=http://localhost:4444 \
        --data grant_type=authorization_code \
        https://oauth2.googleapis.com/token
    

    이 명령어는 애플리케이션에 액세스하는 데 사용할 수 있는 id_token 필드가 있는 JSON 객체를 반환합니다.

애플리케이션에 액세스

앱에 액세스하려면 id_token을 사용하세요.

curl --verbose --header 'Authorization: Bearer ID_TOKEN' URL

갱신 토큰

로그인 과정 중에 생성된 갱신 토큰을 사용하여 새 ID 토큰을 가져올 수 있습니다. 원본 ID 토큰이 만료될 때 유용합니다. 각 ID 토큰은 약 1시간 동안 유효하며, 이 시간 동안 특정 앱에 여러 번 요청을 수행할 수 있습니다.

다음 예에서는 curl을 통해 갱신 토큰을 사용하여 새 ID 토큰을 가져옵니다. 이 예에서 REFRESH_TOKEN은 로그인 과정의 토큰입니다. DESKTOP_CLIENT_IDDESKTOP_CLIENT_SECRET은 로그인 과정에서 사용되는 것과 동일합니다.

curl --verbose \
  --data client_id=DESKTOP_CLIENT_ID \
  --data client_secret=DESKTOP_CLIENT_SECRET \
  --data refresh_token=REFRESH_TOKEN \
  --data grant_type=refresh_token \
  https://oauth2.googleapis.com/token

이 명령어는 앱에 액세스하는 데 사용할 수 있는 새 id_token 필드가 있는 JSON 객체를 반환합니다.

서비스 계정 인증

서비스 계정 JWT 또는 OpenID Connect(OIDC) 토큰을 사용하여 IAP 보안 리소스로 서비스 계정을 인증할 수 있습니다. 다음 표에서는 다양한 인증 토큰과 해당 기능 간의 몇 가지 차이점을 보여줍니다.

인증 기능 서비스 계정 JWT OpenID Connect 토큰
컨텍스트 인식 액세스 지원
OAuth 2.0 클라이언트 ID 요구사항
토큰 범위 IAP 보안 리소스의 URL OAuth 2.0 클라이언트 ID

서비스 계정 JWT로 인증

IAP는 Google ID, Identity Platform, Workforce Identity Federation 구성 애플리케이션의 서비스 계정 JWT 인증을 지원합니다.

JWT를 사용하여 서비스 계정을 인증하는 과정은 다음과 같은 기본 단계로 구성됩니다.

  1. 호출 서비스 계정에 서비스 계정 토큰 생성자 역할 (roles/iam.serviceAccountTokenCreator)을 부여합니다.

    이 역할은 주 구성원에게 JWT와 같은 단기 사용자 인증 정보를 만들 수 있는 권한을 부여합니다.

  2. IAP 보안 리소스에 대한 JWT를 만듭니다.

  3. 서비스 계정 비공개 키를 사용하여 JWT에 서명합니다.

JWT 만들기

생성된 JWT에는 다음 예시와 비슷한 페이로드가 있어야 합니다.

{
  "iss": SERVICE_ACCOUNT_EMAIL_ADDRESS,
  "sub": SERVICE_ACCOUNT_EMAIL_ADDRESS,
  "aud": TARGET_URL,
  "iat": IAT,
  "exp": EXP,
}
  • isssub 필드에 서비스 계정의 이메일 주소를 지정합니다. 이 이메일 주소는 서비스 계정 JSON 파일의 client_email 필드에 있거나 전달됩니다. 일반적인 형식: service-account@PROJECT_ID.iam.gserviceaccount.com

  • aud 필드에 IAP 보안 리소스의 URL을 지정합니다.

  • iat 필드에 현재 유닉스 시간을 지정하고 exp 필드에는 3,600초 이내의 시간을 지정합니다. 이 필드는 JWT의 만료 시점을 정의합니다.

JWT 서명

다음 방법 중 하나를 사용하여 JWT를 서명할 수 있습니다.

  • IAM 사용자 인증 정보 API를 사용하여 비공개 키에 직접 액세스하지 않고 JWT에 서명합니다.
  • 로컬 사용자 인증 정보 키 파일을 사용하여 JWT에 로컬로 서명합니다.
IAM Service Account Credentials API를 사용하여 JWT 서명

IAM Service Account Credentials API를 사용하여 서비스 계정 JWT에 서명합니다. 이 메서드는 서비스 계정과 연결된 비공개 키를 가져와 JWT 페이로드에 서명하는 데 사용합니다. 이렇게 하면 비공개 키에 직접 액세스하지 않고도 JWT에 서명할 수 있습니다.

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

gcloud

  1. 다음 명령어를 실행하여 JWT 페이로드로 요청을 준비합니다.
cat > claim.json << EOM
{
  "iss": "SERVICE_ACCOUNT_EMAIL_ADDRESS",
  "sub": "SERVICE_ACCOUNT_EMAIL_ADDRESS",
  "aud": "TARGET_URL",
  "iat": $(date +%s),
  "exp": $((`date +%s` + 3600))
}
EOM
  1. 다음 Google Cloud CLI 명령어를 사용하여 claim.json의 페이로드에 서명합니다.
gcloud iam service-accounts sign-jwt --iam-account="SERVICE_ACCOUNT_EMAIL_ADDRESS" claim.json output.jwt

요청이 성공하면 output.jwt에 IAP 보안 리소스에 액세스하는 데 사용할 수 있는 서명된 JWT가 포함됩니다.

Python

import datetime
import json

import google.auth
from google.cloud import iam_credentials_v1

def generate_jwt_payload(service_account_email: str, resource_url: str) -> str:
    """Generates JWT payload for service account.

    Creates a properly formatted JWT payload with standard claims (iss, sub, aud,
    iat, exp) needed for IAP authentication.

    Args:
        service_account_email (str): Specifies service account JWT is created for.
        resource_url (str): Specifies scope of the JWT, the URL that the JWT will
            be allowed to access.

    Returns:
        str: JSON string containing the JWT payload with properly formatted claims.
    """
    # Create current time and expiration time (1 hour later) in UTC
    iat = datetime.datetime.now(tz=datetime.timezone.utc)
    exp = iat + datetime.timedelta(seconds=3600)

    # Convert datetime objects to numeric timestamps (seconds since epoch)
    # as required by JWT standard (RFC 7519)
    payload = {
        "iss": service_account_email,
        "sub": service_account_email,
        "aud": resource_url,
        "iat": int(iat.timestamp()),
        "exp": int(exp.timestamp()),
    }

    return json.dumps(payload)

def sign_jwt(target_sa: str, resource_url: str) -> str:
    """Signs JWT payload using ADC and IAM credentials API.

    Uses Google Cloud's IAM Credentials API to sign a JWT. This requires the
    caller to have iap.webServiceVersions.accessViaIap permission on the target
    service account.

    Args:
        target_sa (str): Service Account JWT is being created for.
            iap.webServiceVersions.accessViaIap permission is required.
        resource_url (str): Audience of the JWT, and scope of the JWT token.
            This is the url of the IAP protected application.

    Returns:
        str: A signed JWT that can be used to access IAP protected apps.
            Use in Authorization header as: 'Bearer <signed_jwt>'
    """
    # Get default credentials from environment or application credentials
    source_credentials, project_id = google.auth.default()

    # Initialize IAM credentials client with source credentials
    iam_client = iam_credentials_v1.IAMCredentialsClient(credentials=source_credentials)

    # Generate the service account resource name
    # If project_id is None, use '-' as placeholder as per API requirements
    project = project_id if project_id else "-"
    name = iam_client.service_account_path(project, target_sa)

    # Create and sign the JWT payload
    payload = generate_jwt_payload(target_sa, resource_url)

    # Sign the JWT using the IAM credentials API
    response = iam_client.sign_jwt(name=name, payload=payload)

    return response.signed_jwt

curl

  1. 다음 명령어를 실행하여 JWT 페이로드로 요청을 준비합니다.

    cat << EOF > request.json
    {
      "payload": JWT_PAYLOAD
    }
    EOF
    
  2. IAM을 사용하여 JWT에 서명합니다.

    Service Account Credentials API:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      -d @request.json \
      "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL_ADDRESS:signJwt"
    

    요청이 성공하면 서명된 JWT가 응답에 반환됩니다.

  3. JWT를 사용하여 IAP 보안 리소스에 액세스합니다.

로컬 사용자 인증 정보 키 파일에서 JWT 서명

JWT는 서비스 계정의 비공개 키를 사용하여 서명됩니다.

서비스 계정 키 파일이 있는 경우 JWT에 로컬로 서명할 수 있습니다.

스크립트는 페이로드와 함께 JWT 헤더를 전송합니다. 헤더의 kid 필드에는 서비스 계정 사용자 인증 정보 JSON 파일의 private_key_id 필드에 있는 서비스 계정의 비공개 키 ID를 사용합니다. 이 키는 JWT에 서명하는 데도 사용됩니다.

애플리케이션 액세스

모든 경우에 앱에 액세스하려면 signed-jwt를 사용합니다.

curl --verbose --header 'Authorization: Bearer SIGNED_JWT' URL

OIDC 토큰으로 인증

  1. OAuth 2.0 클라이언트 ID를 만들거나 기존 OAuth 2.0 클라이언트 ID를 사용합니다. 기존 OAuth 2.0 클라이언트 ID를 사용하려면 OAuth 클라이언트를 공유하는 방법의 단계를 따릅니다.
  2. 애플리케이션의 프로그래매틱 액세스 허용 목록에 OAuth ID를 추가합니다.
  3. IAP 보안 프로젝트의 액세스 목록에 기본 서비스 계정이 추가되었는지 확인합니다.

IAP 보안 리소스에 요청할 때는 Authorization 헤더에 토큰을 포함해야 합니다. Authorization: 'Bearer OIDC_TOKEN'

다음 코드 샘플은 OIDC 토큰을 가져오는 방법을 보여줍니다.

기본 서비스 계정의 OIDC 토큰 가져오기

Compute Engine, App Engine 또는 Cloud Run의 기본 서비스 계정용 OIDC 토큰을 가져오려면 다음 코드 샘플을 참고하여 IAP 보안 리소스에 액세스할 수 있는 토큰을 생성하세요.

C#

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


using Google.Apis.Auth.OAuth2;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

public class IAPClient
{
    /// <summary>
    /// Makes a request to a IAP secured application by first obtaining
    /// an OIDC token.
    /// </summary>
    /// <param name="iapClientId">The client ID observed on 
    /// https://console.cloud.google.com/apis/credentials. </param>
    /// <param name="uri">HTTP URI to fetch.</param>
    /// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>
    /// <returns>The HTTP response message.</returns>
    public async Task<HttpResponseMessage> InvokeRequestAsync(
        string iapClientId, string uri, CancellationToken cancellationToken = default)
    {
        // Get the OidcToken.
        // You only need to do this once in your application
        // as long as you can keep a reference to the returned OidcToken.
        OidcToken oidcToken = await GetOidcTokenAsync(iapClientId, cancellationToken);

        // Before making an HTTP request, always obtain the string token from the OIDC token,
        // the OIDC token will refresh the string token if it expires.
        string token = await oidcToken.GetAccessTokenAsync(cancellationToken);

        // Include the OIDC token in an Authorization: Bearer header to 
        // IAP-secured resource
        // Note: Normally you would use an HttpClientFactory to build the httpClient.
        // For simplicity we are building the HttpClient directly.
        using HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return await httpClient.GetAsync(uri, cancellationToken);
    }

    /// <summary>
    /// Obtains an OIDC token for authentication an IAP request.
    /// </summary>
    /// <param name="iapClientId">The client ID observed on 
    /// https://console.cloud.google.com/apis/credentials. </param>
    /// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>
    /// <returns>The HTTP response message.</returns>
    public async Task<OidcToken> GetOidcTokenAsync(string iapClientId, CancellationToken cancellationToken)
    {
        // Obtain the application default credentials.
        GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(cancellationToken);

        // Request an OIDC token for the Cloud IAP-secured client ID.
       return await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId), cancellationToken);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"google.golang.org/api/idtoken"
)

// makeIAPRequest makes a request to an application protected by Identity-Aware
// Proxy with the given audience.
func makeIAPRequest(w io.Writer, request *http.Request, audience string) error {
	// request, err := http.NewRequest("GET", "http://example.com", nil)
	// audience := "IAP_CLIENT_ID.apps.googleusercontent.com"
	ctx := context.Background()

	// client is a http.Client that automatically adds an "Authorization" header
	// to any requests made.
	client, err := idtoken.NewClient(ctx, audience)
	if err != nil {
		return fmt.Errorf("idtoken.NewClient: %w", err)
	}

	response, err := client.Do(request)
	if err != nil {
		return fmt.Errorf("client.Do: %w", err)
	}
	defer response.Body.Close()
	if _, err := io.Copy(w, response.Body); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}

	return nil
}

Java

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


import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.Collections;

public class BuildIapRequest {
  private static final String IAM_SCOPE = "https://www.googleapis.com/auth/iam";

  private static final HttpTransport httpTransport = new NetHttpTransport();

  private BuildIapRequest() {}

  private static IdTokenProvider getIdTokenProvider() throws IOException {
    GoogleCredentials credentials =
        GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(IAM_SCOPE));

    Preconditions.checkNotNull(credentials, "Expected to load credentials");
    Preconditions.checkState(
        credentials instanceof IdTokenProvider,
        String.format(
            "Expected credentials that can provide id tokens, got %s instead",
            credentials.getClass().getName()));

    return (IdTokenProvider) credentials;
  }

  /**
   * Clone request and add an IAP Bearer Authorization header with ID Token.
   *
   * @param request Request to add authorization header
   * @param iapClientId OAuth 2.0 client ID for IAP protected resource
   * @return Clone of request with Bearer style authorization header with ID Token.
   * @throws IOException exception creating ID Token
   */
  public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId)
      throws IOException {

    IdTokenProvider idTokenProvider = getIdTokenProvider();
    IdTokenCredentials credentials =
        IdTokenCredentials.newBuilder()
            .setIdTokenProvider(idTokenProvider)
            .setTargetAudience(iapClientId)
            .build();

    HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(credentials);

    return httpTransport
        .createRequestFactory(httpRequestInitializer)
        .buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent());
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const url = 'https://some.iap.url';
// const targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';

const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth();

async function request() {
  console.info(`request IAP ${url} with target audience ${targetAudience}`);
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.fetch(url);
  console.info(res.data);
}

request().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

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

namespace Google\Cloud\Samples\Iap;

# Imports Auth libraries and Guzzle HTTP libraries.
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

/**
 * Make a request to an application protected by Identity-Aware Proxy.
 *
 * @param string $url The Identity-Aware Proxy-protected URL to fetch.
 * @param string $clientId The client ID used by Identity-Aware Proxy.
 */
function make_iap_request($url, $clientId)
{
    // create middleware, using the client ID as the target audience for IAP
    $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($clientId);
    $stack = HandlerStack::create();
    $stack->push($middleware);

    // create the HTTP client
    $client = new Client([
        'handler' => $stack,
        'auth' => 'google_auth'
    ]);

    // make the request
    $response = $client->get($url);
    print('Printing out response body:');
    print($response->getBody());
}

Python

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

from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests


def make_iap_request(url, client_id, method="GET", **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Args:
      url: The Identity-Aware Proxy-protected URL to fetch.
      client_id: The client ID used by Identity-Aware Proxy.
      method: The request method to use
              ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                If no timeout is provided, it is set to 90 by default.

    Returns:
      The page body, or raises an exception if the page couldn't be retrieved.
    """
    # Set the default timeout, if missing
    if "timeout" not in kwargs:
        kwargs["timeout"] = 90

    # Obtain an OpenID Connect (OIDC) token from metadata server or using service
    # account.
    open_id_connect_token = id_token.fetch_id_token(Request(), client_id)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    resp = requests.request(
        method,
        url,
        headers={"Authorization": "Bearer {}".format(open_id_connect_token)},
        **kwargs
    )
    if resp.status_code == 403:
        raise Exception(
            "Service account does not have permission to "
            "access the IAP-protected application."
        )
    elif resp.status_code != 200:
        raise Exception(
            "Bad response from application: {!r} / {!r} / {!r}".format(
                resp.status_code, resp.headers, resp.text
            )
        )
    else:
        return resp.text

Ruby

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

# url = "The Identity-Aware Proxy-protected URL to fetch"
# client_id = "The client ID used by Identity-Aware Proxy"
require "googleauth"
require "faraday"

# The client ID as the target audience for IAP
id_token_creds = Google::Auth::Credentials.default target_audience: client_id

headers = {}
id_token_creds.client.apply! headers

resp = Faraday.get url, nil, headers

if resp.status == 200
  puts "X-Goog-Iap-Jwt-Assertion:"
  puts resp.body
else
  puts "Error requesting IAP"
  puts resp.status
  puts resp.headers
end

로컬 서비스 계정 키 파일에서 OIDC 토큰 가져오기

서비스 계정 키 파일을 사용하여 OIDC 토큰을 생성하려면 키 파일을 사용하여 JWT 어설션을 만들고 서명한 후 이 어설션을 ID 토큰으로 교환합니다. 다음 Bash 스크립트는 이 프로세스를 보여줍니다.

Bash

#!/usr/bin/env bash
#
# Example script that generates an OIDC token using a service account key file
# and uses it to access an IAP-secured resource

set -euo pipefail

get_token() {
  # Get the bearer token in exchange for the service account credentials
  local service_account_key_file_path="${1}"
  local iap_client_id="${2}"

  # Define the scope and token endpoint
  local iam_scope="https://www.googleapis.com/auth/iam"
  local oauth_token_uri="https://www.googleapis.com/oauth2/v4/token"

  # Extract data from service account key file
  local private_key_id="$(cat "${service_account_key_file_path}" | jq -r '.private_key_id')"
  local client_email="$(cat "${service_account_key_file_path}" | jq -r '.client_email')"
  local private_key="$(cat "${service_account_key_file_path}" | jq -r '.private_key')"

  # Set token timestamps (current time and expiration 10 minutes later)
  local issued_at="$(date +%s)"
  local expires_at="$((issued_at + 600))"

  # Create JWT header and payload
  local header="{'alg':'RS256','typ':'JWT','kid':'${private_key_id}'}"
  local header_base64="$(echo "${header}" | base64 | tr -d '\n')"
  local payload="{'iss':'${client_email}','aud':'${oauth_token_uri}','exp':${expires_at},'iat':${issued_at},'sub':'${client_email}','target_audience':'${iap_client_id}'}"
  local payload_base64="$(echo "${payload}" | base64 | tr -d '\n')"

  # Create JWT signature using the private key
  local signature_base64="$(printf %s "${header_base64}.${payload_base64}" | openssl dgst -binary -sha256 -sign <(printf '%s\n' "${private_key}")  | base64 | tr -d '\n')"
  local assertion="${header_base64}.${payload_base64}.${signature_base64}"

  # Exchange the signed JWT assertion for an ID token
  local token_payload="$(curl -s \
    --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
    --data-urlencode "assertion=${assertion}" \
    https://www.googleapis.com/oauth2/v4/token)"

  # Extract just the ID token from the response
  local bearer_id_token="$(echo "${token_payload}" | jq -r '.id_token')"
  echo "${bearer_id_token}"
}

main() {
  # Check if required arguments are provided
  if [[ $# -lt 3 ]]; then
    echo "Usage: $0 <service_account_key_file.json> <iap_client_id> <url>"
    exit 1
  fi

  # Assign parameters to variables
  SERVICE_ACCOUNT_KEY="$1"
  IAP_CLIENT_ID="$2"
  URL="$3"

  # Generate the ID token
  echo "Generating token..."
  ID_TOKEN=$(get_token "${SERVICE_ACCOUNT_KEY}" "${IAP_CLIENT_ID}")

  # Access the IAP-secured resource with the token
  echo "Accessing: ${URL}"
  curl --header "Authorization: Bearer ${ID_TOKEN}" "${URL}"
}

# Run the main function with all provided arguments
main "$@"

이 스크립트는 다음 단계를 실행합니다.

  1. JSON 키 파일에서 서비스 계정 키 정보를 추출합니다.
  2. IAP 클라이언트 ID를 타겟 잠재 사용자로 포함하여 필요한 필드가 있는 JWT를 만듭니다.
  3. 서비스 계정의 비공개 키를 사용하여 JWT에 서명합니다.
  4. Google의 OAuth 서비스를 통해 이 JWT를 OIDC 토큰으로 교환합니다.
  5. 결과 토큰을 사용하여 IAP 보안 리소스에 인증된 요청을 실행합니다.

이 스크립트를 사용하려면 다음 안내를 따르세요.

  1. 파일에 저장합니다(예: get_iap_token.sh).
  2. 실행 파일로 만듭니다. chmod +x get_iap_token.sh
  3. 다음 세 가지 매개변수를 사용하여 실행합니다.
  ./get_iap_token.sh service-account-key.json \
    OAUTH_CLIENT_ID \
    URL

각 항목의 의미는 다음과 같습니다.

  • service-account-key.json은 다운로드한 서비스 계정 키 파일입니다.
  • OAUTH_CLIENT_ID는 IAP 보안 리소스의 OAuth 클라이언트 ID입니다.
  • URL은 액세스하려는 URL입니다.

그 외 모든 경우에 OIDC 토큰 가져오기

그 외 모든 경우에는 IAM 사용자 인증 정보 API를 사용하여 IAP 보안 리소스에 액세스하기 직전에 타겟 서비스 계정을 가장하여 OIDC 토큰을 생성합니다. 이 프로세스는 다음과 같은 단계로 진행됩니다.

  1. 호출 서비스 계정 (ID 토큰을 가져오는 코드와 연결된 서비스 계정)에 서비스 계정 OpenID Connect ID 토큰 생성자 역할 (roles/iam.serviceAccountOpenIdTokenCreator)을 제공합니다.

    이렇게 하면 호출 서비스 계정이 타겟 서비스 계정을 가장할 수 있습니다.

  2. 호출 서비스 계정이 제공한 사용자 인증 정보를 사용하여 타겟 서비스 계정에서 generateIdToken 메서드를 호출합니다.

    audience 필드를 클라이언트 ID로 설정합니다.

단계별 안내는 ID 토큰 만들기를 참조하세요.

Proxy-Authorization 헤더에서 인증

애플리케이션이 Authorization 요청 헤더를 사용하는 경우 대신 Proxy-Authorization: Bearer 헤더에 ID 토큰을 포함할 수 있습니다. Proxy-Authorization 헤더에 유효한 ID 토큰이 있으면 IAP가 이 토큰을 사용하여 요청을 승인합니다. 요청을 승인하면 IAP가 콘텐츠를 처리하지 않고 애플리케이션에 Authorization 헤더를 전달합니다.

Proxy-Authorization 헤더에 유효한 ID 토큰이 없는 경우 IAP가 Authorization 헤더 처리를 계속 진행하며 요청이 애플리케이션에 전달되기 전에 Proxy-Authorization 헤더를 제거합니다.

다음 단계