Send Docs Feedback

Secure an API with OAuth

What you'll learn

  • 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.

This tutorial shows you how to secure an API with OAuth 2.0.

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 most basic 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 consumer key is also what Edge apps use for an API key when API key security is implemented, often in conjunction with some type of OAuth.

The client credentials grant type in Edge is implemented using policies in API proxies. A typical OAuth flow in 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.

What you'll need

  • An Apigee Edge account. If you don't have one yet, you can sign up with the directions at Creating an Apigee Edge account.
  • cURL installed on your machine to make API calls from the command line.

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 https://enterprise.apigee.com and log in. This is the Edge management UI.
  3. Click APIs in the top menu.

    Before you continue, scroll through your list of API proxies. If you already have one called oauth, click it and skip to the next section to make sure it's configured the same as what's described. If yours is different, either delete it and continue these steps, or modify it to match the configuration described.

  4. Click the add (+) API Proxy button.
  5. In the Build a Proxy wizard, select Proxy bundle and click Next.
  6. Choose the oauth.zip file you downloaded, and click Next.
  7. Click Build.
  8. After the build completes, click the oauth link to view the new proxy in the API proxy editor.
  9. On the API Proxy editor Overview page, click the Deployment drop-down and select test. This is the test environment in your organization.

    At the confirmation prompt, click Deploy.
    When you click the Deployment drop-down again, a green icon indicates that the proxy is deployed to the test environment.

Way to go! You've successfully downloaded and deployed an access token-generating API proxy to your Edge 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 millseconds, 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.

The RefreshAccessToken flow and policy in the API proxy isn't used in this tutorial and isn't supported with the OAuth client credentials grant type.

Create the OAuth-protected API proxy

About the 'mocktarget'

The mocktarget service is hosted at Apigee and returns simple data. In fact, you can access it in a web browser. Try it out by clicking the following:

http://mocktarget.apigee.net/ip

The target returns what you should see when you eventually call this API proxy.

You can also hit http://mocktarget.apigee.net/help to see other API resources that are available in the mocktarget.

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. Click APIs in the top menu.
  2. Click the add (+) API Proxy button.
  3. In the Build a Proxy wizard, select Reverse proxy (most common), and click Next.
  4. Configure the proxy with the following:
    In this field do this
    Proxy Name Enter: helloworld_oauth2
    Project Base Path

    Change to: /v1/hellooauth2

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

    Adding a version number is considered a best practice to version your API. For more information on this important topic, see Versioning Best Practices.

    Existing API

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

    Be sure to use http and not https. This defines the target URL that Apigee Edge invokes on a request to the API proxy.

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

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

  7. On the Virtual Hosts page, click Next.
  8. On the Build page, make sure the test environment is selected, and click Build and Deploy.
  9. On the Summary page, you see an acknowledgment that your new API proxy and an API product were created successfully, and that the API proxy was deployed to your test environment.
  10. Click View the helloworld_oauth2 proxy in the editor to display the Overview page for the API proxy.
    Notice that this time the API proxy is automatically deployed. Click the Deployment drop-down to make sure there's a green deployment dot next to the "test" environment.

About the API product

Without getting into too much detail for this tutorial, an API product in Edge (among other nifty features) generates consumer keys and secrets for developers; or more accurately, for the apps developers register with Edge.

If you're curious, you can view the API product that was automatically created when your API proxy was generated. Select Publish > Products > helloworld_oauth2-Product in the UI.

Notice that the Key Approval Type is Automatic. That means developers get an API key automatically when they register an app, as opposed to you manually approving keys before they're given to developers.

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 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 Edge 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 do this
    First Name Enter: Nigel
    Last Name Enter: Tufnel
    Email Enter: nigel@example.com
    Username Enter: nigel
  4. Click Save.

Register an app

Let's create an app for Nigel.

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

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. On the Developer Apps page (Publish > Developer Apps), click nigel_app.
  2. On the nigel_app page, click Show in the Consumer Key and Consumer Secret columns. Notice that the key/secret are associated with the "helloworld_oauth2 Product" that was automatically created earlier.

  3. Select and copy the Consumer Key and Consumer 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!)

Just for kicks, try calling the protected API proxy that is supposed to return your IP address. Execute the following cURL command in a terminal window, substituting your Edge organization name (remove the curly braces). The word test in the URL is your organization's test environment, the one you deployed your proxies to. Notice that you are not passing an OAuth access token in the call.

http://{org-name}-test.apigee.net/v1/hellooauth2

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

Now we get to the big payoff. You're about to use the Consumer Key and Consumer 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), substituting your Edge organization name, your consumer key, and your consumer secret where indicated (be sure to remove the curly braces):

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
https://{org-name}-test.apigee.net/oauth/client_credential/accesstoken?grant_type=client_credentials \
-d 'client_id={consumer-key}&client_secret={consumer-secret}'

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",
  "developer.email" : "nigel@example.com",
  "token_type" : "BearerToken",
  "client_id" : "xNnREu1DNGfiwzQZ5HUN8IAUwZSW1GZW",
  "access_token" : "GTPY9VUHCqKVMRB0cHxnmAp0RXc0",
  "organization_name" : "myOrg",
  "refresh_token_expires_in" : "0",
  "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 Edge organization name and the access token (remove the curly braces).

curl http://{org-name}-test.apigee.net/v1/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

 

Help or comments?