<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eka Putra on Medium]]></title>
        <description><![CDATA[Stories by Eka Putra on Medium]]></description>
        <link>https://medium.com/@ekaputra07?source=rss-9020aa4dc6d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PnJBD8XFioWMr36Qc-0Qqg.png</url>
            <title>Stories by Eka Putra on Medium</title>
            <link>https://medium.com/@ekaputra07?source=rss-9020aa4dc6d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:45:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ekaputra07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to programmatically access IAP protected apps on Google Cloud]]></title>
            <link>https://ekaputra07.medium.com/how-to-programmatically-access-iap-protected-apps-on-google-cloud-f7ca3302a546?source=rss-9020aa4dc6d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7ca3302a546</guid>
            <category><![CDATA[bearer-token]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[identity-aware-proxy]]></category>
            <category><![CDATA[access-token]]></category>
            <dc:creator><![CDATA[Eka Putra]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 12:21:37 GMT</pubDate>
            <atom:updated>2024-11-26T13:00:40.455Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://cloud.google.com/security/products/iap?hl=en">Cloud Identity-Aware Proxy (IAP)</a> by Google makes it easy to add authentication mechanism to any applications without the need for those apps to manually manage users, passwords, or login flow (at least for the simplest use case).</p><p>It’s basically a managed proxy that sits between you (user) and your web application. This allows us to decouples mechanism for authentication from the application itself.</p><blockquote>For detailed overview about IAP, please heads over to their documentation: <a href="https://cloud.google.com/iap/docs/concepts-overview">https://cloud.google.com/iap/docs/concepts-overview</a>.</blockquote><p>Now if we’re talking about a typical web application, where it has UI that is accessible via web browser, once we setup IAP for it, the sign-in experience will be similar to how we access our Gmail account.</p><p><strong>But what if that application also provides an API that we want to access using CURL or HTTP clients programmatically?</strong></p><p>Well… Google got you covered, simply read this page from start to finish: <a href="https://cloud.google.com/iap/docs/authentication-howto">https://cloud.google.com/iap/docs/authentication-howto</a></p><p>But honestly, I was having problem to digest everything in that page the first time, so many information packed into single page. It’s easy to miss important points if we’re not paying enough attention.</p><p>Therefore here, I try to reorganized those information using simpler terms while also reminds you about key points that makes them works.</p><h3>Our goal: a Bearer token</h3><p>To make an HTTP request to any applications that sits behind IAP, we’ll need to presents some kind of identity token, in this case it need to be a Bearer token in the request headers.</p><p>To be more specific, the Authorization header:</p><pre># example calling our IAP protected API using CURL command<br><br>curl --header &#39;Authorization: Bearer {TOKEN}&#39; \<br>  https://my-service.com/api/endpoint</pre><p>Nothing new right? it’s really common to access protected endpoints using Authorization header. Now let’s look at how to generate one.</p><h3>Methods to generate the token</h3><p>As the <a href="https://cloud.google.com/iap/docs/authentication-howto">documentation</a> says, we can use either <strong>Service Account JWT</strong> token or <strong>OpenID Connect (OIDC) </strong>token. But here I won’t go through any details on what they are or what’s the different between the two to keep this guide short and simple.</p><p>We will only talk about multiple ways to generate them.</p><blockquote><strong>👋 Important:</strong> Whichever method you use, one thing is mandatory. <strong>You need A service account</strong> that have been given access to the IAP protected apps, which mean it is granted an <strong>IAP-Secured Web App User </strong>role<strong>. </strong>(<a href="https://cloud.google.com/iap/docs/managing-access#add_access">here’s how</a> to grant one)</blockquote><p>And from now on, let’s call this service account an <strong>Accessor</strong> <strong>Service Account, </strong>because this<strong> </strong>service account is the one that we allowed to access our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl6rkxUsUJ6PZrhhw4NbiA.png" /><figcaption>Relationship between Service Account, IAP and our target Application.</figcaption></figure><h4><strong>Generate Service Account JWT token</strong></h4><p>Here we’ll create a JWT token from our accessor service account. To generate a valid JWT token we need to <strong>create JWT payload and then sign it</strong>.</p><p>Here’s how we create the payload:</p><pre>import datetime<br>import jwt<br><br># this is service account that had given access to our app<br>ACCESSOR_SERVICE_ACCOUNT = &quot;accessor-sa@12345678.iam.gserviceaccount.com&quot;<br><br># API endpoint that we want to access<br>RESOURCE_URL = &quot;https://my-service.com/api/v1&quot;<br><br># Generate JWT payload, we set expiry to 1hr after creation<br>iat = datetime.datetime.now(tz=datetime.timezone.utc).timestamp()<br>exp = int(iat) + 3600<br>payload = {<br>      &#39;iss&#39;: ACCESSOR_SERVICE_ACCOUNT,<br>      &#39;sub&#39;: ACCESSOR_SERVICE_ACCOUNT,<br>      &#39;aud&#39;: RESOURCE_URL,<br>      &#39;iat&#39;: iat,<br>      &#39;exp&#39;: exp,<br>}</pre><blockquote><strong>👋</strong><em> </em><strong>Important: </strong>Resource URL must match the URL that we’re trying to access. We can’t use <em>https://api.com</em> as resource URL to generate the token while trying to access <a href="https://api.com/v1/users"><em>https://api.com/v1/users</em></a></blockquote><p>It’s simple, nothing special other than we need to follow the payload fields and format as well as pay attention to the resource URL. Now what left for us is to sign it.</p><p>This is where sometime people get confused. There are two ways to sign the payload and it’s up to you to pick one that you prefer.</p><p><strong>#1. Sign payload using Application Default Credentials (ADC)</strong></p><p>This is<strong> </strong>suitable for environments where ADC is available, such as:</p><ul><li><em>Locally</em>, if you’re able to execute gcloud command then you have ADC points to your GCP account credentials already.</li><li><em>Apps that running inside GCP infrastructure</em> <em>(Cloud Run, App Engine, GKE, etc)</em>. If you’re going to call IAP protected apps from other apps in those platforms, they’re likely have service account assigned to them (either default or the one you created). That service account credentials become ADC in that environment and can be used to sign JWT payload.</li></ul><blockquote><em>👋 </em><strong>Important:</strong> If our ADC is a User Account or not the same Service Account as our accessor SA, they needs to have <a href="https://cloud.google.com/iam/docs/service-account-permissions"><strong>serviceAccountTokenCreator</strong></a> role, otherwise they won’t allowed to generate token for other SA (our accessor SA).</blockquote><p>This method allows us to sign the payload without having direct access to the credentials key file of our accessor service account (better security practice).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgDltlOsX_XNo3571mcGMA.png" /><figcaption>User or Service Account’s ADC used to sign the payload.</figcaption></figure><p>Now let’s use it to sign our JWT payload:</p><pre>import json<br>import google.auth<br>from google.cloud import iam_credentials_v1<br><br># we&#39;re using application default credentials<br>adc, _ = auth.default()<br><br># create the IAM client<br>iam_client = iam_credentials_v1.IAMCredentialsClient(credentials=adc)<br><br># we got the token!<br>token = iam_client.sign_jwt(<br>  name=iam_client.service_account_path(&#39;-&#39;, ACCESSOR_SERVICE_ACCOUNT),<br>  payload=json.dumps(payload), # &lt;-- pass json-encoded payload from previous step<br>).signed_jwt</pre><p><strong>#2. Sign payload using service account’s credentials key file</strong></p><p>If you’re comfortable working with credentials key file directly, this method will works as well. It involves downloading our accessor credentials key file locally or embed it into the application that will call the IAP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3D2AD6gsn4bz0j3GqpSUA.png" /><figcaption>Sign using credentials key file.</figcaption></figure><blockquote>I personally prefer the ADC method as I’m trying to avoid having credential file as a plain text inside my service or in my computer.</blockquote><p>Signing with credentials key file:</p><pre>import json<br>import jwt<br><br># read the key file<br>with open(&quot;path/to/credentials.json&quot;, &#39;r&#39;) as f:<br>  key_data = json.load(f)<br><br>private_key_id = key_data[&quot;private_key_id&quot;]<br>private_key = key_data[&quot;private_key&quot;]<br><br># Sign JWT with private key and store key id in the header<br>additional_headers = {&#39;kid&#39;: private_key}<br><br># we got the token!<br>token = jwt.encode(<br>      payload, # &lt;-- pass payload from previous step<br>      private_key_id,<br>      headers=additional_headers,<br>      algorithm=&#39;RS256&#39;,<br>)</pre><p>That’s how we create JWT token from service account, now let’s try the OIDC Token method.</p><h4>Creating <strong>OpenID Connect (</strong>OIDC) token</h4><p>OIDC token is relatively simpler to create compared to Service Account JWT token, but you need to pay attention on few things that are easy to be missed, potentially causing a failure to generate the token.</p><p><strong>Keep in mind of these points:</strong></p><ol><li>Make sure you have correct IAP client ID, can bee copied from <strong>Credentials</strong> section of <strong>Api &amp; Services</strong> console in GCP console.</li><li>Make sure you are using Accessor service account credentials and <strong>not </strong>user account credentials.</li></ol><p>Now let’s demonstrate a way to generate OIDC token using Application Default Credentials inside GCP environment (Cloud Run, AppEngine, GKE, etc.):</p><pre>from google.auth.transport.requests import Request<br>from google.oauth2 import id_token<br>import requests<br><br>IAP_CLIENT_ID = &quot;123456-abcdef.apps.googleusercontent.com&quot;<br><br># we got the token!<br>token = id_token.fetch_id_token(Request(), IAP_CLIENT_ID)</pre><p>Note that if you try to run above code locally, it will complains about metadata server is not reachable. Of course, since we’re outside of GCP.</p><p>But what we can do is to download the service account’s credentials key file and set the GOOGLE_APPLICATION_CREDENTIALS variable.</p><pre># tell google auth library where to look for credentials<br>export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json</pre><pre>import os<br>from google.auth.transport.requests import Request<br>from google.oauth2 import id_token<br>import requests<br><br>IAP_CLIENT_ID = &quot;123456-abcdef.apps.googleusercontent.com&quot;<br><br># we got the token!<br>token = id_token.fetch_id_token(Request(), IAP_CLIENT_ID)</pre><p>Those are few methods to create Bearer token to access IAP protected applications. Which one to use depends on your preference and your environment from where you’re willing to access the application from.</p><p>That’s all for now, if I missed something or I did confuse you, don’t hesitate to hit me in the comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7ca3302a546" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>