• Nonexistent node nid: 14763.
  • Nonexistent node nid: 14763.
Was this helpful?

It's important to protect your API from unauthorized access. One way to do that is to validate API keys (also called "public keys", "consumer keys" or "app keys").

The tutorial Add and configure your first API shows how to create your first API proxy. This tutorial shows you how to secure an API using the VerifyAPIKey policy.

In this tutorial, you create a new version of the API proxy to the Yahoo weather service that adds the VerifyAPIKey policy automatically to the API proxy when you create it. The advantage of creating a new version of the API proxy is that Apigee Edge creates all of the policies necessary to enforce API keys for you. If you have an existing API proxy and want to add API key validation, you can add those policies manually at any time.

Before you start, here is some information about API products, API keys, and apps.

The Relationship between organization, API products, apps, and API keys

Apigee Edge generates an API key for an app that is registered in an organization and is associated with an API product.

  • An organization represents a container that holds all the objects in an Apigee account. The name of your organization is typically the API project name you provided when you signed up for an Apigee account.
  • An API product is a bundle of API proxies combined with a service plan that sets limits on access to those APIs. API products are the central mechanism that Apigee Edge uses for authorization and access control to your APIs.
  • An app is a client-side app that a developer registers with an API product. Registering the app with the API product generates the API key.
  • An API key is a string with authorization information that a client-side app uses to access the resources exposed by the API product. The API key is generated when a registered app is associated with an API product.

    Developers must provide this key in requests to your API's resources.

You enforce API key validation by applying the VerifyAPIKey policy (see Enforce access control using VerifyAPIKey). At runtime, that policy verifies the following:

  • That the API key is valid
  • That it hasn't been revoked
  • That it matches the API key for the API product that exposes the requested resources

When an app makes a call to your API, the app must supply the correct key. If the key is valid, the call can access the resources exposed in the API product. If the key is invalid, it results in an authorization failure.

What you'll do in this tutorial

This tutorial shows you how to use the Apigee Edge management UI to create an API proxy and secure it using the VerifyAPIKey policy. In this tutorial, you add the VerifyAPIKey policy to the API proxy when you initially create the proxy. You can also add the VerifyAPIKey policy to an existing proxy.

For more information on API keys, see Secure APIs with API keys.

Step 1: Create an API proxy

Configure an API proxy for the Yahoo! Weather API. This repeats some of the same actions as in the tutorial Add and configure your first API. However, you'll also add security to your API proxy in this step.

  1. Login to https://enterprise.apigee.com.
  2. In the API Platform UI, select the APIs tab.
  3. Click (+) API Proxy.
  4. Make the following selections and entries in the New API Proxy page.
    Field Value Description
    Choose your starting point
    Starting point radio button Existing Backend Service The API proxy will target an existing service accessible over the Internet.
    Backend Service URL http://weather.yahooapis.com The URL that the API Platform invokes on behalf of apps that call your API through the API proxy URL. This is the URL for the Yahoo! Weather API.
    Identify your API proxy
    Name weatherapikey The name displayed for your API
    Project Base Path /v1/weatherapikey The base path that the API platform uses to construct the API proxy URL. Apps will call this URL to invoke your API. 1
    Description Yahoo weather proxy The description of the API.
    Add Features
    Secure with API Keys selected Adds API key-based authentication to your API proxy. When this option is selected, the Impose Quota per Developer option becomes selectable.
    Impose Quota per Developer selected Adds a policy that limits the number of request messages that can be submitted to your API proxy by an individual app over an interval of time.
    Publish API Product cleared When you select the Secure with API Keys option, the Publish API Product option is automatically selected. For the purposes of this tutorial, be sure to clear this option.
    Enable Direct Browser Access for Your API selected Enables CORS (cross-origin resource sharing) to allow a browser to make direct requests to another domain.

    1 The API proxy URL is of the form http(s)://{org}-{env}.apigee.net/{base_path}, where {org} is your organization, {env} is the environment, and {base_path} is the root under which all services are provided by the API. You specify the base path (in this tutorial, /v1/weatherapikey) in the dialog. Apigee Edge then constructs the API proxy URL. So if your organization is myorg, and the environment is test, the constructed API proxy URL is http://myorg-test.apigee.net/v1/weatherapikey. Apps will call this URL to invoke the API.

    The filled-in page should look like this:

  5. Click Build to save the entries you made in the page.
    In response, you should see an acknowledgment that your new API proxy was successfully created and deployed in the 'test' environment.
  6. Click Close.

Learn more:

Step 2: Define API resources

  1. In the management UI, select the APIs tab to display the API Proxies page.
  2. Click weatherapikey in the API Proxies table.
  3. In the Resources section, click the (+) Add Resource button.
  4. Enter the following values:
    • Name: forecast
    • Proxy Endpoint: default
    • Verb: GET
    • Path: /forecastrss

  5. Click the check icon in the Actions columns to validate the resource.
  6. Click Save.

The resource is added to the API proxy.

Learn more:

Step 3: Examine generated policies

  1. Open the API Proxy Editor by clicking the Develop button in the details page for the weatherapikey API proxy.
  2. On the left side of the API Proxy Editor, select PreFlow under Proxy Endpoints > default to show the generated policies in the Policy Designer.

    For more information on Flows and Endpoints, see Understanding APIs and API proxies.

Notice that three policies have already been added to your API proxy's request message flow:

Name Policy Type Description
Verify API Key VerifyAPIKey Verifies the API key for an API product, returns an error if it is invalid, and if it is valid, looks up the attributes from the API product.
Remove Query Param AssignMessage Modifies request messages in the API proxy flow. Here, the policy is used to prevent the API key from being sent to the backend URL.
Add Quota Quota Enforces a limit on the number of API calls made by apps over an interval of time.

Also notice what's been added for these policies to the API Proxy Editor:

  • The policies are added to various views in the Proxy Editor.
  • The policies are added to the list of policies in the Navigator view.
  • The policies are added to the Designer view, which is a visual representation of your proxy's message flows.
  • The XML for each policy is displayed in the Code view.
  • The XML element and attribute values for each policy are displayed in the Property Inspector.

The VerifyAPIKey policy

The VerifyAPIKey policy validates API keys. Typically, you want API key validation to happen as soon as a request is received by your API proxy. The PreFlow is always the first flow to execute at an endpoint, and the ProxyEndpoint is the first endpoint in the request pipeline. Because the VerifyAPIKey policy is the first policy in the PreFlow, the API key will be validated by the policy as soon as it's received by the API proxy. With the policy in place, this means that a call to the API won't work unless it includes the appropriate API key.

Click the Verify API Key policy icon, and examine the XML for the policy in the Code view. You can also view the values for the policy's XML elements and attributes in the Property Inspector. Here's what you should see in the Property Inspector:

The XML for the policy should look something like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<VerifyAPIKey async="false" continueOnError="false" enabled="true" name="Verify-Api-Key">
    <DisplayName>Verify API Key</DisplayName>
    <APIKey ref="request.queryparam.apikey"/>
</VerifyAPIKey>   

Note especially the ref parameter of the <APIKey> element, which identifies where the policy should check for the API key. API keys can be located in a query parameter, a form parameter, or an HTTP header. Apigee Edge provides a message variable for each type of location.

Request variable Where expected key location is provided
request.queryparam.{queryparam_name} query parameter
request.header.{header_name} header
request.formparam.{formparam_name} form parameter

In this case, the key is expected in a query parameter named apikey.

<apikey ref="request.queryparam.apikey" />

The AssignMessage policy

The next policy to be enforced in the PreFlow is an AssignMessage policy named Remove Query Param. It strips the verified API key from the outbound request to the backend service. Only the Apigee Edge security layer needs to be aware of the API key.

Examine the XML for the AssignMessage policy. Here's what you should see in the Property Inspector:

The XML for the policy should look like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Remove-Query-Param">
    <DisplayName>Remove Query Param</DisplayName>
    <Remove>
        <QueryParams>
            <QueryParam name="apikey"/>
        </QueryParams>
    </Remove>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

The AssignMessage policy defines a set of elements that perform actions such as populating or modifying HTTP headers, query parameters, and XML or JSON payload content. For example, the AssignMessage policy above uses a <Remove> element to remove the query parameter named apikey from the HTTP request message attached to the flow.

An AssignMessage policy is named that way because the policy requires a message to be 'assigned' as a variable. By assigning a message to a variable, you make the message available to the message flow. Other policies in the flow can then access the variable's content.

For example, the following creates an HTTP message and assigns it to a variable named Request.

<AssignTo createNew="true" transport="http" type="request">Request</AssignTo>

The type value indicates the type of the message: request or response.

If the createNew parameter is set to false, as it is in the following <AssignTo> element, no variable is created.

<AssignTo createNew="false" transport="http" type="request"></AssignTo>

However, in this case, you can use the AssignMessage policy to modify the request or response message where the policy is attached.

The Quota policy

The final policy in the PreFlow is a Quota policy named Add Quota. It enforces a limit on the number of API calls made by apps over an interval of time. The limit is set in the API product. For example, you may want to limit apps to 1 request per minute, or to 10,000 requests per month.

Examine the XML for the Quota. Here's what you should see in the Property Inspector:

The XML for the policy should look like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Quota async="false" continueOnError="false" enabled="true" name="Add-Quota">
    <DisplayName>Add Quota</DisplayName>
    <Allow countRef="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.limit" count="2000"/>
    <Interval ref="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.interval">1</Interval>
    <Distributed>true</Distributed>
    <Synchronous>true</Synchronous>
    <TimeUnit ref="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.timeunit">month</TimeUnit>
</Quota>

The Quota policy sets values for the maximum count of messages for the quota (2000), the time interval (1), and the time unit (month). The policy also references variables that are populated by Apigee Edge when the VerifyAPIKey policy is enforced. These values take precedence over the values set in the policy. For example, the following specifies a maximum message count for the quota based on the limit set in the API product that is used in validating the request:

<Allow countRef="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.limit" count="5000"/>

Learn more:

Step 4: Add an API product

An API product is a collection of API resources combined with a service plan and presented to developers as a bundle. The product can also include some metadata specific to your business for monitoring or analytics.

API products are also the central mechanism for authorization and access control to your APIs. API keys are provisioned for API products. An API key is generated when a registered app is associated with an API product. After you create an API product you associate it with an app to generate the API key.

  1. In the management UI, click the Publish tab, then Products.
  2. Click (+) Product.
  3. Enter or select the following in the Add Product dialog fields:

     

    Field Value
    Display Name Free API Product
    Description Free API Product
    Environment test
    Access Internal only
    Key approval type Automatic
    (the API key is automatically approved after it has been generated)
    Quota 10 requests per hour
    (limits the number of requests to 10 per hour)
    Allowed Oauth Scopes Read

    The filled-in dialog should look like this:

  4. In the Resources section, choose:
    • API Proxyweatherapikey
    • Revision: 1
    • Resource Path: /forecastrss**


       
  5. Click Import Resource. The resource path is added, and the weatherapikey API proxy is automatically added to the API Proxies for Product section.
  6. Click Save.
    Your new product is listed on the Products page.

Learn more: Creating API products

Step 5: Add a developer

Before an API key can be generated, you need to add an app and associate it with an API product. However, you can't create an app without a developer, so you need to have at least one developer registered in your organization.

If you have a public API product that developers can sign up for through a portal, developers can register themselves. However, for the purposes of the tutorial, you don't have a developer portal. You add a developer directly in the management UI.

  1. In the management UI, click the Publish tab, then Developers.
  2. Click (+) Developer.
  3. In the New Developer dialog, enter the following values:
    • First Name: Jane
    • Last Name: Tutorial
    • Email address: janetutorial@example.com
  4. Click Save.
    The new developer appears in the list of developers on the Developers page.

Learn more:

Nonexistent node nid: 14763.

Step 6: Create an app and register the app with the API product

Now that you have an API product and a developer you can create an app and register the app with the API product. You register the app to generate an API key for your API products. You can then distribute the key to app developers so they can access the features in the API products from the app.

You create and register an app in the management UI.

  1. In the API Platform UI, click the Publish tab, then Developer Apps.
  2. Click (+) Developer App.
  3. In the Add an App dialog, enter the following values:
    • Display Name: Weather API Key App
    • Developer: Jane Tutorial (janetutorial@example.com)
    • Callback URL: login.weatherapp.com
  4. Associate the app with a product: In the Products section, click + Product, select Free API Product, and click the check mark icon to accept the changes.
  5. Click Save.
    The new app appears in the list  of apps on the Developer Apps page.
  6. Select Weather API Key App in the list of apps. This opens the details page for the app.
  7. Because you selected Key Approval Type: Automatic in a previous step, the API key is automatically approved and you can view it immediately. (If you had selected Approval Type: Manual, you would need to click Approve in the Actions column for Free API Product to approve the API key.)
  8. Click Weather API Key App in the Developer Apps list to view the app details.
  9. In the Products section, next to the entry for Free API Product, click Show in the Consumer Key and Consumer Secret columns to display the generated keys.

    The Consumer Key is another name for the API key and is the only key an app needs to access the forecast resource through your API proxy . The Consumer Secret is needed (along with the Consumer Key) in securing an API through OAuth 2.0. See, for example, Secure APIs with OAuth 2.0: client credentials.

Learn more:

Nonexistent node nid: 14763.
.

Step 7: Test the VerifyAPIKey policy

To ensure that the VerifyAPIKey policy is working correctly, you need to test it by making a call to the API proxy with a valid API key. You can request the API proxy in a browser, from the Trace page of the API proxy, from the Apigee Console, or by using cURL. The URL to request is in the form:

http://{org-name}-test.apigee.net/v1/weatherapikey/forecastrss?w=12797282&apikey=IEYRtW2cb7A5Gs54A1wKElECBL65GVls

Substitute your Apigee organization name for {org-name} and the correct Consumer Key value.

If you omit the API key from the request, or specify an invalid key value, you will receive an error response in the form:

{"fault":{"faultstring":"Failed to resolve API Key variable null","detail":{"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}

To use a browser:

  1. Enter the URL in a browser window.

To use the Trace page:

  1. In management UI, click the APIs tab. If the API Platform page is not open, click here.
  2. Click weatherapikey in the API Proxies table.
  3. On the weatherapikey detail page, click the Trace button to access the Trace page.
  4. On the Trace page, choose the test environment.
  5. Click Start Trace Session.
  6. Request your API.
    You can then use the Trace page to examine each part of the request and response.

To use the Apigee Console:

  1. From the Trace page, click Send with the Apigee Console, just below the Send button in the Send Requests area of the Trace page.
    The console appears in another browser window.
  2. Enter the URL of your API.
  3. Click Send.
  4. Switch back to the Trace page to see the trace.
  5. Enter the HTTP verb and URL for the weather forecast resource, and provide the API key. (You can also enter the URL for the API desired resource, without the GET verb, in your favorite browser.)

To use cURL:

  1. Install cURL.
    The cURL tool is a convenient way to submit URL-based commands from a command line.

  2. Use cURL to request the URL:

    curl "http://myorg-test.apigee.net/v1/weatherapikey/forecastrss?w=12797282&apikey=bagW9lvG8dX4ooUC5wcqW4PP1KZX5jPQ"

Step 8: Send the API key as a header

The default configuration of the VerifyAPIKey policy in your API proxy specifies to send the API key as a query parameter. In this step, you modify the policy to send the API key as a header instead.

  1. In the management UI, select the APIs tab to display the API Proxies page.
  2. Click weatherapikey in the API Proxies table.
  3. On the weatherapikey detail page, click the Develop button to open the API Proxy Editor.
  4. On the left side of the API Proxy Editor, select PreFlow under Proxy Endpoints > default to show the policies in the Policy Designer.
  5. Select the Verify API Key policy in the request.
  6. Change the ref value of the <APIKey> element to request.header.apikey.

    <APIKey ref="request.header.apikey"/>

    This value specifies that the API key is passed in a header named apikey.

     
  7. Click  Save.
  8. Click the Trace button to access the Trace page.
  9. Open the Apigee Console by clicking Send with the Apigee Console, just below the Send button in the Send Requests area of the Trace page.
  10. Enter the URL of your API, but omit the apikey query parameter.
  11. Click Headers, just below the URL.
  12. Add a header named apikey, with a value of the API key.
  13. Click Send.

Appendix: Retrieving and revoking the API key

As an admin for your organization, you can retrieve the API key for an app. You can also revoke an API key for an app. You might need to revoke an API key if you find a serious error in an API resource. When you revoking an API key, it blocks access to the associated API product, and all apps that are assigned that key can no longer access the resources exposed by that API product. If there are problems with those resources, revoking the key can prevent errors in your developers' applications.

To retrieve an API key:

  1. In the management UI, click the Publish tab, then Developer Apps.
  2. In the Developer Apps page, select the app (for example, Weather API Key App).
    This displays the details page for the app. The keys appear when you click Show in the Consumer Key and Consumer Secret columns.

     

To revoke an API key:

  1. In the management UI, click the Publish tab, then Developer Apps.
  2. On the Developer Apps page, select the app (for example, Weather API Key App).
  3. Click Edit to modify the developer app, and in the Products section of the page, click Revoke in the Actions column.

    After you revoke the API key, 'Revoke' changes to 'Approve' in the Actions column. If you click Approve, it makes the API key available again to the app.

     

    If you click Remove in the Actions column, it removes the API product from the app.

Learn more: Control API access

Help or comments?

  • Something's not working: See Apigee Support
  • Something's wrong with the docs: Click Send Feedback in the lower right.
    (Incorrect? Unclear? Broken link? Typo?)