Secure an API with OAuth

This tutorial explains how to:

  • Download and deploy a sample API proxy.
  • Create an OAuth-protected API proxy.
  • Create a product, developer, and app.
  • Exchange credentials for an OAuth access token.
  • Call an API with an access token.

OAuth is an authorization protocol that enables apps to access information on behalf of users without requiring users to divulge their username and password.

With OAuth, security credentials (such as username/password or key/secret) are exchanged for an access token. For example:

joe:joes_password (username:password) or
Nf2moHOASMJeUmXVdDhlMbPaXm2U7eMc:unUOXYpPe74ZfLEb (key:secret)

becomes something like:

b0uiYwjRZLEo4lEu7ky2GGxHkanN

The access token is a random string of characters and is temporary (it should expire after a relatively short time), so passing it around to authenticate a user in an app workflow is much more secure than passing around actual credentials.

The OAuth 2.0 specification defines different mechanisms, called "grant types," for distributing access tokens for apps. The one grant type defined by OAuth 2.0 is called "client credentials." In this grant type, OAuth access tokens are generated in exchange for client credentials, which are consumer key/consumer secret pairs, like the example above.

The client credentials grant type in Apigee is implemented using policies in API proxies. A typical OAuth flow involves two steps:

  • Call API proxy 1 to generate an OAuth access token from client credentials. An OAuth v2.0 policy on the API proxy handles this.
  • Call API proxy 2 to send the OAuth access token in an API call. The API proxy verifies the access token using an OAuth v2.0 policy.

Download and deploy a token-generating API proxy

In this step, you'll create the API proxy that generates an OAuth access token from a consumer key and consumer secret sent in an API call. Apigee provides a sample API proxy that does this. You'll download and deploy the proxy now, then use it later in the tutorial. (You could build this API proxy easily yourself. This download and deploy step is for convenience and to show you how easy it is to share proxies that have already been created.)

  1. Download the 'oauth' sample API proxy ZIP file to any directory on your file system.
  2. Go to the Apigee UI and sign in.
  3. Select Develop > API Proxies in the left navigation bar.
  4. Click + Proxy.
    Create proxy button
  5. In the Create Proxy wizard, select Upload proxy bundle.
  6. Choose the oauth.zip file you downloaded, and click Next.
  7. Click Create.
  8. After the build completes, click the Edit proxy to view the new proxy in the API proxy editor.
  9. Click the Revision drop-down and select the revision number to deploy the proxy.

You've successfully downloaded and deployed an access token-generating API proxy to your Apigee organization.

View the OAuth flow and policy

Let's take a closer look at what the API proxy contains.

  1. In the API proxy editor, click the Develop tab. In the left Navigator pane, you'll see two policies. You'll also see two POST flows in the Proxy Endpoints section.
  2. Click AccessTokenClientCredential under Proxy Endpoints.

    In the XML code view, you'll see a Flow called AccessTokenClientCredential:

    <Flow name="AccessTokenClientCredential">
        <Description/>
        <Request>
            <Step>
                <Name>GenerateAccessTokenClient</Name>
            </Step>
        </Request>
        <Response/>
        <Condition>(proxy.pathsuffix MatchesPath "/accesstoken") and (request.verb = "POST")</Condition>
    </Flow>
    

    A flow is a processing step in an API proxy. In this case, the flow is triggered when a certain condition is met (it's called a "conditional flow"). The condition, defined in the <Condition> element, says that if the API proxy call is made to the /accesstoken resource, and the request verb is POST, then execute the GenerateAccessTokenClient policy, which generates the access token.

  3. Now let's look at the policy the conditional flow will trigger. Click the GenerateAccessTokenClient policy icon in the flow diagram.

    The following XML configuration is loaded into the code view:

    <OAuthV2 name="GenerateAccessTokenClient">
        <!-- This policy generates an OAuth 2.0 access token using the client_credentials grant type -->
        <Operation>GenerateAccessToken</Operation>
        <!-- This is in milliseconds, so expire in an hour -->
        <ExpiresIn>3600000</ExpiresIn>
        <SupportedGrantTypes>
            <!-- This part is very important: most real OAuth 2.0 apps will want to use other
             grant types. In this case it is important to NOT include the "client_credentials"
             type because it allows a client to get access to a token with no user authentication -->
            <GrantType>client_credentials</GrantType>
        </SupportedGrantTypes>
        <GrantType>request.queryparam.grant_type</GrantType>
        <GenerateResponse/>
    </OAuthV2>
    

    The configuration includes the following:

    • The <Operation>, which can be one of several predefined values, defines what the policy is going to do. In this case, it's going to generate an access token.
    • The token will expire 1 hour (3600000 milliseconds) after being generated.
    • In <SupportedGrantTypes>, the OAuth <GrantType> expected to be used is client_credentials (exchanging a consumer key and secret for an OAuth token).
    • The second <GrantType> element tells the policy where to look in the API call for the grant type parameter, as required by the OAuth 2.0 specification. (You'll see this in the API call later). The grant type could also be sent in the HTTP header (request.header.grant_type) or as a form parameter (request.formparam.grant_type).

You don't need to do anything else with the API proxy at the moment. In later steps, you'll use this API proxy to generate an OAuth access token. But first, you need to do a few more things:

  • Create the API proxy you actually want to secure with OAuth.
  • Create a few more artifacts that will result in the consumer key and consumer secret you need to exchange for an access token.

Create the OAuth-protected API proxy

Now you're going to create the API proxy you want to protect. This is the API call that returns something you want. In this case, the API proxy will call Apigee's mocktarget service to return your IP address. BUT, you'll get to see it only if you pass a valid OAuth access token with your API call.

The API proxy you create here will include a policy that checks for an OAuth token in the request.

  1. Select Develop > API Proxies in the left navigation bar.
  2. Click + Proxy.
    Create proxy button
  3. In the Build a Proxy wizard, select Reverse proxy (most common).
  4. Configure the proxy with the following:
    In this field do this
    Proxy Name Enter: helloworld_oauth2
    Project Base Path

    Change to: /hellooauth2

    The Project Base Path is part of the URL used to make requests to the API proxy.

    Existing API

    Enter: https://mocktarget.apigee.net/ip

    This defines the target URL that Apigee invokes on a request to the API proxy.

    Description Enter: hello world protected by OAuth
  5. Click Next.
  6. On the Common policies page:
    In this field do this
    Security: Authorization Select:
    • OAuth 2.0

    These options are very handy. They'll automatically add two policies to your API proxy and create an API product.

  7. Click Next.
  8. On the Summary page, under Optional Deployment, select an environment, and click Create.
  9. Click Edit proxy to display the Overview page for the API proxy.
    The API proxy is automatically deployed for you. (It may take a few moments for the deployment to complete.)

View the policies

Let's take a closer look at what you've created.

  1. In the API proxy editor, click the Develop tab. You'll see that two policies have been added to the request flow of the API proxy:
    • Verify OAuth v2.0 Access Token – Checks the API call to make sure a valid OAuth token is present.
    • Remove Header Authorization – An Assign Message policy that removes the access token after it's checked, so that it doesn't get passed to the target service. (If the target service needed the OAuth access token, you wouldn't use this policy).
  2. Click the Verify OAuth v2.0 Access Token icon in the flow view and look at the XML below it in the code pane.

    <OAuthV2 async="false" continueOnError="false" enabled="true" name="verify-oauth-v2-access-token">
        <DisplayName>Verify OAuth v2.0 Access Token</DisplayName>
        <Operation>VerifyAccessToken</Operation>
    </OAuthV2>
    

    Notice that the <Operation> is VerifyAccessToken. The Operation defines what the policy is supposed to do. In this case, it's going to check for a valid OAuth token in the request.

Add an API product

To add an API product using the Apigee UI:

  1. Select Publish > API Products.
  2. Click +API Product.
  3. Enter the Product Details for your API product.
    Field Description
    Name Internal name of the API product. Do not specify special characters in the name.
    Note: You cannot edit the name once the API product is created.
    Display name Display name for the API product. The display name is used in the UI and you can edit it at any time. If not specified, the Name value will be used. This field is auto-filled using the Name value; you can edit or delete its contents. The display name can include special characters.
    Description Description of the API product.
    Environment Environments to which the API product will allow access. Select the environment to which you deployed the API proxy.
    Access Select Public.
    Automatically approve access requests Enable automatic approval of key requests for this API product from any app.
    Quota Ignore for this tutorial.
    Allowed OAuth Scopes Ignore for this tutorial.
  4. In the API resources section, add the API proxy you just created.
  5. In the Paths section, add the path "/".
  6. Click Save.

Add a developer and app to your organization

Next, you're going to simulate the workflow of a developer signing up to use your APIs. Ideally, developers register themselves and their apps through your developer portal. In this step, though, you'll add a developer and an app as an administrator.

A developer will have one or more apps that call your APIs, and each app gets a unique consumer key and consumer secret. This key/secret-per-app also gives you, the API provider, more granular control over access to your APIs and more granular analytics reporting on API traffic, because Apigee knows which developer and app belong to which OAuth token.

Create a developer

Let's create a developer named Nigel Tufnel.

  1. Select Publish > Developers in the menu.
  2. Click + Developer.
  3. Enter the following in the New Developer window:
    In this field Enter
    First Name Nigel
    Last Name Tufnel
    Username nigel
    Email nigel@example.com
  4. Click Save.

Register an app

Let's create an app for Nigel.

  1. Select Publish > Apps.
  2. Click + App.
  3. Enter the following in the New App window:
    In this field do this
    Name and Display Name Enter: nigel_app
    Developer Click Developer and select: Nigel Tufnel (nigel@example.com)
    Callback URL and Notes Leave blank
  4. Under Products, click Add Product.
  5. Add the API product you just created.
  6. Click Create.

Get the consumer key and consumer secret

Now you'll get the consumer key and consumer secret that will be exchanged for an OAuth access token.

  1. Ensure that the nigel_app page is displayed. If not, on the Apps page (Publish > Apps), click nigel_app.
  2. On the nigel_app page, click Show in the Key and Secret columns. Notice that the key/secret are associated with the API product that you created earlier.

  3. Select and copy the Key and Secret. Paste them in a temporary text file. You'll use them in a later step, where you call the API proxy that will exchange these credentials for an OAuth access token.

Try calling the API to get your IP address (fail!)

Try calling the protected API proxy that you just created. Notice that you are not passing an OAuth access token in the call.

curl -v -k https://EXTERNAL_IP/hellooauth2

Where EXTERNAL_IP is the address of your internet-facing IP address, as defined when Apigee was installed. See Configure routing.

Because the API proxy has the Verify OAuth v2.0 Access Token policy checking for a valid OAuth token in the request, the call should fail with the following message:

{"fault":{"faultstring":"Invalid access token","detail":{"errorcode":"oauth.v2.InvalidAccessToken"}}}

In this case, failure is good! It means your API proxy is much more secure. Only trusted apps with a valid OAuth access token can successfully call this API.

Get an OAuth access token

Next, you will use the key and secret you copied and pasted into a text file and exchange them for an OAuth access token. You're now going to make an API call to the API sample proxy you imported, oauth, which will generate an API access token.

Using that key and secret, make the following cURL call (note that the protocol is https):

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
"https://EXTERNAL_IP/oauth/client_credential/accesstoken?grant_type=client_credentials" \
-d "client_id={key}&client_secret={secret}"

Note that if you're using a client like Postman to make the call, the client_id and client_secret go in the Body of the request and must be x-www-form-urlencoded.

You should get a response like this:

{
  "issued_at" : "1466025769306",
  "application_name" : "716bbe61-f14a-4d85-9b56-a62ff8e0d347",
  "scope" : "",
  "status" : "approved",
  "api_product_list" : "[helloworld_oauth2-Product]",
  "expires_in" : "3599", //--in seconds
  "developer.email" : "nigel@example.com",
  "token_type" : "BearerToken",
  "client_id" : "xNnREu1DNGfiwzQZ5HUN8IAUwZSW1GZW",
  "access_token" : "GTPY9VUHCqKVMRB0cHxnmAp0RXc0",
  "organization_name" : "myOrg",
  "refresh_token_expires_in" : "0", //--in seconds
  "refresh_count" : "0"
}

You got your OAuth access token! Copy the access_token value (without the quote marks) and paste it into your text file. You'll use it in a moment.

What just happened?

Remember previously when you looked at that "conditional flow" in the oauth proxy, the one that said if the resource URI is /accesstoken and the request verb is POST, to execute the GenerateAccessTokenClient OAuth policy that generates an access token? Your cURL command met those conditions, so the OAuth policy was executed. It verified your consumer key and consumer secret and exchanged them for an OAuth token that expires in 1 hour.

Call the API with an access token (success!)

Now that you have an access token, you can use it to call the API proxy. Make the following cURL call. Substitute your Apigee organization name and the access token (remove the curly braces).

curl https://EXTERNAL_IP/hellooauth2 -H "Authorization: Bearer {access-token}"

You should now get a successful call to the API proxy that returns your IP address. For example:

{"ip":"::ffff:192.168.14.136"}

You can repeat that API call for close to an hour, after which time the access token will expire. To make the call after an hour, you'll need to generate a new access token using the previous steps.

Congratulations! You've created an API proxy and protected it by requiring that a valid OAuth access token be included in the call.

Related topics