Apps running on Google Cloud Platform (GCP) managed platforms such as App Engine can avoid managing user authentication and session management by using Cloud Identity-Aware Proxy (Cloud IAP) to control access to them. Cloud IAP can not only control access to the app, but it also provides information about the authenticated users, including the email address and a persistent identifier to the app in the form of new HTTP headers.
Objectives
Require users of your App Engine app to authenticate themselves by using Cloud IAP.
Access users' identities in the app to display the current user's authenticated email address.
Costs
This tutorial uses the following billable components of Google Cloud Platform:
You can use the pricing calculator to generate a cost estimate based on your projected usage. New GCP users might be eligible for a free trial.
When you finish this tutorial, you can avoid continued billing by deleting the resources you created. For more information, see Cleaning up.
Before you begin
-
Sign in to your Google Account.
If you don't already have one, sign up for a new account.
-
In the GCP Console, on the project selector page, select or create a GCP project.
- Install and initialize the Cloud SDK.
Background
This tutorial uses Cloud IAP to authenticate users. This is only one of several possible approaches. To learn more about the various methods to authenticate users, see the Authentication concepts section.
The Hello user-email-address app
The app for this tutorial is a minimal Hello world App Engine app,
with one non-typical feature: instead of "Hello world" it displays
"Hello user-email-address", where
user-email-address is the authenticated
user's email address.
This functionality is possible by examining the authenticated information that Cloud IAP adds to each web request it passes through to your app. There are three new request headers added to each web request that reaches your app. The first two headers are plain text strings that you can use to identify the user. The third header is a cryptographically signed object with that same information.
X-Goog-Authenticated-User-Email: A user's email address identifies them. Don't store personal information if your app can avoid it. This app doesn't store any data; it just echoes it back to the user.X-Goog-Authenticated-User-ID: This user ID assigned by Google doesn't show information about the user, but it does allow an app to know that a logged-in user is the same one that was previously seen before.X-Goog-Iap-Jwt-Assertion: You can configure Google Cloud Platform (GCP) apps to accept web requests from other cloud apps, bypassing Cloud IAP, in addition to internet web requests. If an app is so configured, it's possible for such requests to have forged headers. Instead of using either of the plain text headers previously mentioned, you can use and verify this cryptographically signed header to check that the information was provided by Google. Both the user's email address and a persistent user ID are available as part of this signed header.
If you are certain that the app is configured so that only internet web requests can reach it, and that no one can disable the Cloud IAP service for the app, then retrieving a unique user ID takes only a single line of code:
user_id = request.headers.get('X-Goog-Authenticated-User-ID')
However, a resilient app should expect things to go wrong, including unexpected configuration or environmental issues, so we instead recommend creating a function that uses and verifies the cryptographically signed header. That header's signature cannot be forged, and when verified, can be used to return the identification.
Create the source code
Use a text editor to create a file named
main.py, and paste the following code in it:import sys from flask import Flask app = Flask(__name__) CERTS = None AUDIENCE = None def certs(): import requests global CERTS if CERTS is None: response = requests.get( 'https://www.gstatic.com/iap/verify/public_key' ) CERTS = response.json() return CERTS def get_metadata(item_name): import requests endpoint = 'http://metadata.google.internal' path = '/computeMetadata/v1/project/' path += item_name response = requests.get( '{}{}'.format(endpoint, path), headers = {'Metadata-Flavor': 'Google'} ) metadata = response.text return metadata def audience(): global AUDIENCE if AUDIENCE is None: project_number = get_metadata('numeric-project-id') project_id = get_metadata('project-id') AUDIENCE = '/projects/{}/apps/{}'.format( project_number, project_id ) return AUDIENCE def validate_assertion(assertion): from jose import jwt try: info = jwt.decode( assertion, certs(), algorithms=['ES256'], audience=audience() ) return info['email'], info['sub'] except Exception as e: print('Failed to validate assertion: {}'.format(e), file=sys.stderr) return None, None @app.route('/', methods=['GET']) def say_hello(): from flask import request assertion = request.headers.get('X-Goog-Iap-Jwt-Assertion') email, id = validate_assertion(assertion) page = "<h1>Hello {}</h1>".format(email) return pageThis
main.pyfile is explained in detail in the Understanding the code section later in this tutorial.Create another file called
requirements.txt, and paste the following into it:Flask>=1.0.0 cryptography python-jose[cryptography] requestsThe
requirements.txtfile lists any non-standard Python libraries your app needs App Engine to load for it:Flaskis the Python web framework used for the app.cryptographyis a module that provides strong cryptographic functions.python-jose[cryptography]provides the JWT checking and decoding function.requestsretrieves data from web sites.
Create a file named
app.yamland put the following text in it:runtime: python37The
app.yamlfile tells App Engine which language environment your code requires.
Understanding the code
This section explains how the code in main.py works. If you just want to run
the app, you can skip ahead to the
Deploy the app
section.
The following code is in the main.py file. When a an HTTP GET request to
the home page is
received by the app, the Flask framework invokes the say_hello function:
@app.route('/', methods=['GET'])
def say_hello():
assertion = request.headers.get('X-Goog-Iap-Jwt-Assertion')
email, id = validate_assertion(assertion)
page = "<h1>Hello {}</h1>".format(email)
return page
The say_hello function gets the JWT assertion header value that
Cloud IAP added from
the incoming request and calls a function to validate that cryptographically
signed value. The first value returned (email) is then used in a minimal web
page that it creates and returns.
def validate_assertion(assertion):
from jose import jwt
try:
info = jwt.decode(
assertion,
certs(),
algorithms=['ES256'],
audience=audience()
)
return info['email'], info['sub']
except:
print('Failed to validate assertion: {}'.format(e), file=sys.stderr)
return None, None
The validate_assertion function uses the jwt.decode function from the
third-party jose library to verify that the assertion is properly signed,
and to extract the payload information from the assertion. That information is
the authenticated user's email address and a persistent unique ID for the user.
If the assertion cannot be decoded, this function returns None for each of
those values and prints a message to log the error.
Validating a JWT assertion requires knowing the public key certificates of the entity that signed the assertion (Google in this case), and the audience the assertion is intended for. For an App Engine app, the audience is a string with GCP project identification information in it. This function gets those certificates and the audience string from the functions preceding it.
def audience():
global AUDIENCE
if AUDIENCE is None:
project_number = get_metadata('numeric-project-id')
project_id = get_metadata('project-id')
AUDIENCE = '/projects/{}/apps/{}'.format(
project_number, project_id
)
return AUDIENCE
You can look up the GCP project's numeric ID and name and put those in the
source code yourself, but the audience function does that for you by querying
the standard metadata service made available to every App Engine app.
Because the metadata service is external to the app code, that result is saved
in a global variable that is returned without having to look metadata up
in subsequent calls.
def get_metadata(item_name):
import requests
endpoint = 'http://metadata.google.internal'
path = '/computeMetadata/v1/project/'
path += item_name
response = requests.get(
'{}{}'.format(endpoint, path),
headers = {'Metadata-Flavor': 'Google'}
)
metadata = response.text
return metadata
The App Engine metadata service (and similar metadata services for other
GCP computing services) looks like a web site and is queried by
standard web queries. However, it isn't actually an external site, but an
internal feature that returns requested information about the running
app, so it is safe to use http instead of https requests.
It's used to get the current GCP identifiers needed to define the
JWT assertion's intended audience.
def certs():
global CERTS
if CERTS is None:
resp = requests.get(
'https://www.gstatic.com/iap/verify/public_key'
)
CERTS = resp.json()
return CERTS
Verification of a digital signature requires the public key certificate of the signer. Google provides a web site that returns all of the currently used public key certificates. These results are cached in case they're needed again in the same app instance.
Deploying the app
After you have the three code files saved, you can deploy the app and then enable Cloud IAP to require users to authenticate before they can access the app.
In your terminal window, go to the directory containing the
main.py,app.yaml, andrequirements.txtfiles, and deploy the app to App Engine:gcloud app deployWhen prompted, select a nearby region.
When asked if you want to continue with the deployment operation, enter
Y.Within a few minutes, your app is live on the internet.
View the app:
gcloud app browseIn the output, copy
web-site-url, the web address for the app.In a browser window, paste
web-site-urlto open the app.A
Hello Noneweb page displays because you're not yet using Cloud IAP so no user information is sent to the app.
Enable Cloud IAP
Now that an App Engine instance exists, you can protect it with Cloud IAP:
In the Google Cloud Platform Console, go to the Identity-Aware Proxy page.
Because this is the first time you've enabled an authentication option for this project, you see a message that you must configure your OAuth consent screen before you can use Cloud IAP.
Click Configure Consent Screen.
On the OAuth Consent Screen tab of the Credentials page, complete the following fields:
In the Application name field, enter
IAP Example.In the Support email field, enter your email address.
In the Authorized domain field, enter the hostname portion of the app's URL, for example,
iap-example-999999.appspot.com. Press theEnterkey after entering the hostname in the field.In the Application homepage link field, enter the URL for your app, for example,
https://iap-example-999999.appspot.com/.In the Application privacy policy line field, use the same URL as the homepage link for testing purposes.
Click Save. When prompted to create credentials, you can close the window.
In the GCP Console, go to the Identity-Aware Proxy page.
To refresh the page, click Refresh refresh. The page displays a list of resources you can protect.
In the IAP column, click to turn on Cloud IAP for the app.
In your browser, go to
web-site-urlagain.Instead of the web page, there is a login screen to authenticate yourself. When you log in, you're denied access because Cloud IAP doesn't have a list of users to allow through to the app.
Add authorized users to the app
In the GCP Console, go to the Identity-Aware Proxy page.
Select the checkbox for the App Engine app, and then click Add Member.
Enter
allAuthenticatedUsers, and then select the Cloud IAP/IAP-Secured Web App User role.Click Save.
Now any user that Google can authenticate can access the app. If you want, you can restrict access further by only adding one or more people or groups as members:
Any Gmail or G Suite email address
A Google Group email address
A G Suite domain name
Access the app
In your browser, go to
web-site-url.To refresh the page, click Refresh refresh.
On the login screen, log in with your Google credentials.
The page displays a "Hello user-email-address" page with your email address.
If you still see the same page as before, there might be an issue with the browser not fully updating new requests now that you enabled Cloud IAP. Close all browser windows, reopen them, and try again.
Authentication concepts
There are several ways an app can authenticate its users and restrict access to only authorized users. Common authentication methods, in decreasing level of effort for the app, are listed in the following sections.
| Option | Advantages | Disadvantages |
|---|---|---|
| App authentication |
|
|
| OAuth2 |
|
|
| Cloud IAP |
|
|
App-managed authentication
With this method, the app manages every aspect of user authentication on its own. The app must maintain its own database of user credentials and manage user sessions, and it needs to provide functions to manage user accounts and passwords, check user credentials, as well as issue, check, and update user sessions with each authenticated login. The following diagram illustrates the app-managed authentication method.
As shown in the diagram, the app must store user credentials so it can provide a way for a user to log in, after which it creates and maintains information about the user's session. When the user makes a request to the app, the request must include session information that the app is responsible for verifying.
The main advantage of this approach is that it is self-contained and under the control of the app. The app doesn't even need to be available on the internet. The main disadvantage is that the app is now responsible for providing all account management functionality and protecting all sensitive credential data.
External authentication with OAuth2
A good alternative to handling everything within the app is to use an external identity service, such as Google, that handles all user account information and functionality and is responsible for safeguarding sensitive credentials. When a user tries to log in to the app the request is redirected to the identity service, which authenticates the user and then redirect the request back to the app with necessary authentication information provided. For more information, see Authenticating as an end user.
The following diagram illustrates the external authentication with the OAuth2 method.
The flow in the diagram begins when the user sends a request to access the app. Instead of responding directly, the app redirects the user's browser to Google's identity platform, which displays a page to log in to Google. After successfully logging in, the user's browser is directed back to the app. This request includes information that the app can use to look up information about the now authenticated user, and the app now responds to the user.
This method has many advantages for the app. It delegates all account management functionality and risks to the external service, which can improve login and account security without the app having to change. However, as is shown in the preceding diagram, the app must have access to the internet to use this method. The app is also responsible for managing sessions after the user is authenticated.
Cloud Identity-Aware Proxy
The third approach, which this tutorial covers, is to use Cloud IAP to handle all authentication and session management with any changes to the app. Cloud IAP intercepts all web requests to your app, blocks any that haven't been authenticated, and passes others through with user identity data added to each request.
The request handling is shown in the following diagram.
Requests from users are intercepted by Cloud IAP, which blocks unauthenticated requests. Authenticated requests are passed on to the app, provided that the authenticated user is in the list of allowed users. Requests passed through Cloud IAP have headers added to them identifying the user who made the request.
The app no longer needs to handle any user account or session information. Any operation that needs to know a unique identifier for the user can get that directly from each incoming web request. However, this can only be used for computing services that support Cloud IAP, such as App Engine and load balancers. You cannot use Cloud IAP on a local development machine.
Cleaning up
To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
- In the GCP Console, go to the Projects page.
- In the project list, select the project you want to delete and click Delete delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.