OAuth has emerged as the leading authorization protocol for APIs. The version of OAuth that is covered in detail in this topic is defined in the OAuth 2.0 Specification

OAuth is a protocol that enables app end users to authorize apps to act on their behalf. Apps do so by obtaining access tokens from API providers. The API provider authenticates the app end user's credentials, ensures that the user has authorized the app, and then issues an access token to the app. When the app consumes a protected API, Apigee Edge checks the access token to ensure that it is valid and that it has not expired. As an API provider, you need to expose endpoints that enable apps to get access tokens.

To make it easy for you to start using OAuth, Apigee Edge enables you to configure and enforce OAuth using policies, without requiring you to write any code. In this topic you will learn how to protect your APIs, how to obtain access tokens, and how to use those access tokens to access protected APIs.

The default OAuth configuration for your organization

For convenience, all organizations on Apigee Edge come preconfigured with a set of OAuth 2.0 endpoints that implement the client credentials grant type. The client credentials grant type defines a procedure for issuing access tokens in exchange for app credentials. These app credentials are simply the consumer key and secret pair that Apigee Edge issues for each app that is registered in an organization. 'Client credentials' refers to the consumer key and secret pair itself.

To learn more about issuing credentials to apps using Edge Developer Services, see Registering apps.

For this reason, it is relatively simple to 'step up' your API security scheme from API key validation to OAuth client credentials. Both schemes use the same consumer key and secret to validate the client app. The difference is that client credentials provides an extra layer of control, since you can easily revoke an access token when needed, without requiring you to revoke the app's consumer key. To work with the default OAuth endpoints, you can use any consumer key and secret generated for app in your organization to retrieve access tokens from the token endpoint. (You can even enable client credentials for apps that already have consumer keys and secrets.)

The full specification for the client credentials grant can be found in the OAuth 2.0 Specification.

Client credentials are sometimes also called "API key and secret" or "app key and secret". The terms are interchangeable and refer to the same credentials.

Protect your API with a policy

Before you can use access tokens, you need to configure your APIs to validate OAuth access tokens at runtime. To do this, you configure an API proxy to validate access tokens. This means that every time an app makes a request to consume one of your APIs, the app must present a valid access token along with the API request. Apigee Edge handles the complexity behind generating, storing, and validating the access tokens that are presented.

You can easily add OAuth verification to an API when you create a new API proxy. When you are creating a new API proxy, you can Add Features. As shown below, you can add verification of OAuth 2.0 access tokens by selecting the radio button next to Secure with OAuth v2.0 Access Tokens. When you select this option, two policies will be attached to the newly created API proxy, one to verify access tokens and another to strip the access token after it has been verified.

In addition, when you select the Secure with OAuth v2.0 Access Tokens option, the Publish API Product checkbox becomes selectable and is automatically selected. Check this if you want to automatically generate a product when you build the new API proxy. The autogenerated product will be created with an association to the new API proxy. If you have an existing product with which you want to associate this new API, be sure to clear this checkbox so that you don't create an unnecessary product. For information about products, see What is an API product?

If you need to enable access token verification for API proxy that already exists, all you need to do is attach a policy of type OAuthV2 to the API that you want to protect. OAuthV2 policies work by specifying an operation. If you want to validate access tokens, you specify the operation called VerifyAccessToken. (Other types of operations that are supported by the OAuthV2 policy type are GenerateAccessToken and GenerateRefreshToken. You will learn about those operations when you set up OAuth endpoints.)

VerifyOAuthTokens policy of type OAuthV2

An example policy to validate access tokens looks like the following. (The settings are explained in the table below.)

<OAuthV2 name="VerifyOAuthTokens"> 
  <Operation>VerifyAccessToken</Operation> 
</OAuthV2>

Policy settings

Name Description Default Required?
OAuthV2 The policy type
name The name of the policy, which is referenced in the API proxy Endpoint configuration. N/A Yes
Operation The operation to be executed by the OAuthV2 policy. By specifying VerifyAccessToken, you configure the policy to check requests for access tokens, and to verify that the access token is valid, has not expired, and is approved to consume the requested API resource (URI). (To make this check, the policy reads the API product that the app is approved to consume.) N/A Yes

To create this policy in the management UI, navigate to APIs > API Proxies.

From the list of API proxies, select weatherapi.

From the Overview for the weatherapi, select the Develop view.

From the drop-down menu, select New Policy > OAuth v2.0

After you select the OAuth v2.0 policy, the New Policy configuration menu will display.

Give your policy a descriptive name, and be sure to select Attach Policy, Flow PreFlow, and Request as policy attachment settings.

Select Add and the policy is created and attached to the weatherapi's request PreFlow.

After you add the policy, the request PreFlow configuration below will display in the Designer pane.

If you are working locally in a text editor or IDE, you attach the Policy to the request PreFlow of the API proxy that you want to protect:

<PreFlow>
  <Request>
    <Step><Name>VerifyOAuthTokens</Name></Step>
  </Request>
</PreFlow>

By attaching the policy to the request PreFlow, you ensure that the policy is always enforced on all request messages.

You have now secured an API with OAuth 2.0 client credentials. The next step is to learn how to obtain an access token, and use it to access the secure API.

Using an access token to access a protected resource

Now that the weatherapi is secured with OAuth 2.0, apps must present access tokens to consume the API. To access a protected resource, the app presents an access token in the request as an "Authorization" HTTP header as follows:

$ curl -H "Authorization: Bearer ylSkZIjbdWybfs4fUQe9BqP0LH5Z" http://{org_name}-test.apigee.net/weather/forecastrss?w=12797282

Because the API has an OAuthV2 policy attached, Apigee Edge will verify that the access token presented is valid, and then grants access to the API, returning the weather report to the app that made the request.

But how do apps get access tokens? We will cover that in the next section.

How to exchange client credentials for an access token

Apps obtain access tokens by presenting their consumer key/secret pairs to the token endpoint. The token endpoint is configured in the API proxy called oauth. So apps need to call the API exposed by the oauth API proxy to get an access token. After the app has an access token, it then can call the weatherapi repeatedly, until the access token expires, or the access token is revoked.

Now you need to shift gears to think of yourself as an app developer. You want to call the weatherapi, so you need to get an access token for your app. The first thing you need to do is get a consumer key and secret pair (otherwise known as an API key or an app key).

You can get a consumer key and secret by registering an app in your organization on Apigee Edge.

You can see all of the apps in your organization in the Apigee Edge management UI.

The list of apps that are registered in your organization will display.

(If no apps display, you can learn how to register an app in the topic called Registering apps.)

Select an app from the list to view its detailed profile.

In the detail view for the app you selected, note the fields for Consumer Key and Consumer Secret. These two values are the client credentials that you will use to obtain an OAuth access token.

You can also obtain the consumer key and secret for an app by calling the management API. First, get the list of apps in your organization by making the following API call:
$ curl https://api.enterprise.apigee.com/v1/o/{org_name}/apps \
-u myname:mypass 

This call returns a list of apps by app ID.

[ "da496fae-2a04-4a5c-b2d0-709278a6f9db", "50e3e831-175b-4a05-8fb6-05a54701af6e" ]

You can retrieve an app's profile by making a simple GET call on the app ID:

$ curl https://api.enterprise.apigee.com/v1/o/{org_name}/apps/{app_id} \
-u myname:mypass 

For example:

$ curl https://api.enterprise.apigee.com/v1/o/{org_name}/apps/da496fae-2a04-4a5c-b2d0-709278a6f9db \
-u myname:mypass 

The API call returns the profile of the app you specified. For example, an app profile for weatherapp has the following JSON representation:

{
  "accessType" : "read",
  "apiProducts" : [ ],
  "appFamily" : "default",
  "appId" : "da496fae-2a04-4a5c-b2d0-709278a6f9db",
  "attributes" : [ ],
  "callbackUrl" : "http://weatherapp.com",
  "createdAt" : 1380290158713,
  "createdBy" : "noreply_admin@apigee.com",
  "credentials" : [ {
    "apiProducts" : [ {
      "apiproduct" : "PremiumWeatherAPI",
      "status" : "approved"
    } ],
    "attributes" : [ ],
    "consumerKey" : "bBGAQrXgivA9lKu7NMPyoYpVKNhGar6K",
    "consumerSecret" : "hAr4Gn0gA9vAyvI4",
    "expiresAt" : -1,
    "issuedAt" : 1380290161417,
    "scopes" : [ ],
    "status" : "approved"
  } ],
  "developerId" : "5w95xGkpnjzJDBT4",
  "lastModifiedAt" : 1380290158713,
  "lastModifiedBy" : "noreply_admin@apigee.com",
  "name" : "weatherapp",
  "scopes" : [ ],
  "status" : "approved"
}

Note the values for consumerKey and consumerSecret. You use these credentials to obtain an access token by presenting them as Basic Authentication credentials in an HTTP request, as shown below. The grant type is presented as a query parameter to the request. (Be sure to change the value of the variable {org_name} to reflect the name of your organization on Apigee Edge.)

Create a request to obtain an access token

In the following request, substitute the value of your consumerKey for client_id. Substitute the value of the associated consumerSecret for client_secret.

$ curl https://{org_name}-test.apigee.net/oauth/client_credential/accesstoken?grant_type=client_credentials -X POST -d 'client_id=bBGAQrXgivA9lKu7NMPyoYpVKNhGar6K&client_secret=hAr4Gn0gA9vAyvI4'

API Services verifies the consumer key and secret and then generates a response containing the access token for this app:

{
  "issued_at" : "1380892555397",
  "application_name" : "957aa73f-25c2-4ead-8021-adc01f0d2c6b",
  "scope" : "",
  "status" : "approved",
  "api_product_list" : "[oauth-test]",
  "expires_in" : "3599",
  "developer.email" : "tesla@weathersample.com",
  "organization_id" : "0",
  "client_id" : "bBGAQrXgivA9lKu7NMPyoYpVKNhGar6K",
  "access_token" : "ylSkZIjbdWybfs4fUQe9BqP0LH5Z",
  "organization_name" : "rqa",
  "refresh_token_expires_in" : "0",
  "refresh_count" : "0"
}

Note the access_token value in the response above. This is the access token that the app will use to gain runtime access to protected resources. The access token for this app is ylSkZIjbdWybfs4fUQe9BqP0LH5Z.

You now have a valid access token, ylSkZIjbdWybfs4fUQe9BqP0LH5Z, that can be used to access protected APIs.

Working with the default OAuth configuration

Each organization (even a free trial org) on Apigee Edge is provisioned with an OAuth token endpoint. The endpoint is preconfigured with policies in the API proxy called oauth. You can begin using the token endpoint as soon as you create an account on Apigee Edge.

The default OAuth endpoint exposes the following endpoint URI:

/oauth/client_credential/accesstoken

Publish this URI to developers who need to obtain access tokens. App developers configure their apps to call this endpoint, presenting their consumer key and secret pairs to obtain access tokens.

The default client credentials token endpoint is exposed over the network at the following URL:

https://{org_name}-{env_name}.apigee.net/oauth/client_credential/accesstoken

For example, if your organization name is "apimakers", the URL would be:

https://apimakers-test.apigee.net/oauth/client_credential/accesstoken

This is the URL that developers call to obtain access tokens.

By default, out-of-the-box OAuth endpoints are only deployed in the test environment. Before they are available in prod, you must explicitly deploy the API proxy called oauth to prod.

3-legged OAuth configurations

Three-legged OAuth configurations (authorization code, implicit and password grant types) require you, the API provider, to authenticate app end users. Since every organization authenticates users in different ways, some policy customization or code is required to integrate OAuth with your user store. For example, all of your users may be stored in Active Directory, in an LDAP, or some other user store. To get three-legged OAuth up and running, you need to integrate a check against this user store into the overall OAuth flow.

You can see an example of how to do this in a sample API proxy on GitHub. For a fully configured API proxy that supports authorization code, implicit, and client credentials grant types, along with a sample login app, see the OAuth Login App sample on GitHub.

To learn how to configure 3-Legged OAuth endpoints, see OAuth endpoints.

OAuth 1.0a

For details on the OAuth 1.0a policy, see OAuth v1.0a policy.

A fully-functional 3-legged OAuth 1.0a sample is available in the API Platform samples on GitHub.

Get help

For help, see Apigee Customer Support.

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?)