Lab 6 - Securing APIs (OAuth)
Overview
There are several out-of-the-box security policies that Apigee Edge provides to protect your APIs. These security policies must be used appropriately based upon your use cases. Apigee Edge supports:
API Keys
API key validation is the simplest form of app-based security that you can configure for an API. Apps simply present an API key, and Apigee Edge checks to see that the API key is in an approved state for the resource being requested. For this reason the security associated with API keys is limited. API keys can easily be extracted from app code and used to access an API. You may find that API keys work better as unique app identifiers than as security tokens. For more information, see API Keys.
OAuth v2.0
Here's the definition of OAuth from the OAuth 2.0 IETF specification. "The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf."
All requests from the app for protected resources from the backend service is negotiated using an access token. Access tokens are long random strings generated by an authorization server after appropriate app and/or user credentials are presented. Tokens are used to validate requests for protected resources. If an app is compromised, the resource server can revoke it's access token. In that case, the end user does not need to change her username/password on the resource server, her app simply needs to renegotiate for a new access token.
To go beyond app identification using API Keys, Apigee Edge provides comprehensive support for OAuth v2.0. Apigee Edge includes an OAuth 2.0 authorization server implementation that lets you register apps and secure API proxies with OAuth 2.0 using the four grant types that are part of OAuth 2.0. For more information, see OAuth 2.0 and the OAuth the Big Picture Apigee eBook.
OAuth v1.0a
OAuth 1.0a defines a standard protocol that enables app users to authorize apps to consume APIs on their behalf, without requiring app users to disclose their passwords to the app in the process. Apigee Edge enables you to protect APIs in a way that ensures that an app uses has authorized the app to consume an API. Edge also provides policy-based functionality for configuring the endpoints that app developers can use to obtain access tokens. For more information, see OAuth v1.0a policy.
SAMLApigee Edge enables you to authenticate and authorize apps that are capable of presenting SAML tokens. A SAML token is a digitally signed fragment of XML that presents a set of "assertions". These assertions can be used to enforce authentication and authorization.
To use SAML terminology, Apigee Edge can function as a service provider (SP) or an Identity Provider (IP). When Apigee Edge validates SAML tokens on inbound requests from apps, it acts in the role of SP. (API Services can also act in the IP role, when generating SAML tokens to be used when communicating with backend services. For details on SAML validation, see SAML Assertion policies.
Content Based Security
Message content is a significant attack vector used by malicious API consumers. API Services provides a set of Policy types to mitigate the potential for your backend services to be compromised by attackers or by malformed request payloads.
JSON threat protection
JSON attacks attempt to use structures that overwhelm JSON parsers to crash a service and induce application-level denial-of-service attacks.
Such attacks can be mitigated using the JSONThreatProtection Policy type.
See JSON Threat Protection policy.
XML threat protection
XML attacks attempt to use structures that overwhelm XML parsers to crash a service and induce application-level denial-of-service attacks.
Such attacks can be mitigated using the XMLThreatProtection Policy type.
See XML Threat Protection policy.
General content protection
Some content-based attacks use specific constructs in HTTP headers, query parameters, or payload content to attempt to execute code. An example is SQL-injection attacks. Such attacks can be mitigated using the Regular Expression Protection Policy type.
See Regular Expression Protection policy.
Data Masking
Apigee Edge enables developers to capture message content to enable runtime debugging of APIs calls. In many cases, API traffic contains sensitive data, such credit cards or personally identifiable health information (PHI) that needs to filtered out of the captured message content.
To meet this requirement, Edge defines 'mask configurations' that enable you to specify data that will be filtered out of trace sessions. Masking configurations can be set globally (at the organization-level) or locally (at the API proxy level). Role-based capabilities govern which users have access to the data that is defined as sensitive.
For more information, see Data Masking
Objectives
The objective of this lesson is to get you familiar with Apigee’s API Key Verification and OAuth 2.0 Token Validation policies.
As discussed in the Overview section, API Key Verification policy enables you to identify the API consumer and prevents unidentified API consumers from being able to call your APIs. You will implement an API Key Verification policy in this lesson to get familiar with several associated concepts such as: API Key, API Secret, API Products and Developer Apps.
Identifying an API consumer is beneficial from an analytics and audit perspective, but in many situations, simply identifying the API consumer is not secure enough. To add an additional level of security, in this lesson you will replace the API Key Verification policy with an OAuth 2.0 Token Validation policy using the client-credentials two-legged OAuth flow.
Prerequisites
-
Lab 5 is completed
-
A preliminary understanding of OAuth 2.0
-
Apigee Oauth proxy deployed to your organization
Estimated Time: 60 mins
-
**Adding an API Key Verification Policy **
a. Go to the Apigee Edge Management UI browser tab
b. Using the ‘New Policy’ drop-down from the ‘Develop’ tab of your proxy, add the ‘Verify API Key’ policy with the following properties:
i. Policy Display Name: **Verify API Key** ii. Policy Name: **Verify-API-Key** iii. Attach Policy: **Checked** iv. Flow: **Flow PreFlow, Proxy Endpoint default** v. Segment: **Request**
c. The ‘Verify API Key’ policy will get added after the ‘Response Cache’ policy. Drag and move the ‘Verify API Key’ policy to be before the ‘Response Cache’ policy
Note: It depends on your use case, but typically API Key verification should be one of the first policies in the flow. In this scenario, we verify the API Key before the Response Cache policy to ensure that an API Consumer whose API Key may have been revoked is not able to get the data from the cache.
a. Examine the XML configuration in the ‘Code’ panel (or properties using the ‘Property Inspector’ panel) associated with the ‘Verify API Key’ policy. 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>
<FaultRules/>
<Properties/>
<APIKey ref="request.queryparam.apikey"/>
</VerifyAPIKey>
(You can find the policy xml here. Click the “Raw” button and copy/paste into your policy editor).
Note the <APIKey> element, which identifies where the policy should check for the API key. In this example, the policy looks for the API key in a query parameter named 'apikey'. 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. For policy reference information, see Verify API Key policy.
-
Removing the API Key from the query parameters
a. Using the ‘New Policy’ drop-down from the ‘Develop’ tab of your proxy, add the ‘Assign Message’ policy with the following properties:
i. Policy Display Name: **Remove APIKey QP ** ii. Policy Name: **Remove-APIKey-QP** iii. Attach Policy: **Checked** iv. Flow: **Flow PreFlow, Proxy Endpoint default** v. Segment: **Request**
b. The ‘Remove APIKey QP’ policy will get added after the ‘Response Cache’ policy. Drag and move the ‘Remove APIKey QP’ policy to be before the ‘Response Cache’ policy
a. For the ‘Remove APIKey QP’ policy, change the XML configuration of the policy using the ‘Code: Remove APIKey QP’ panel as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Remove-APIKey-QP">
<DisplayName>Remove APIKey QP</DisplayName>
<Remove>
<QueryParams>
<QueryParam name="apikey"></QueryParam>
</QueryParams>
</Remove>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
(You can find the policy xml here. Click the “Raw” button and copy/paste into your policy editor).
As a security measure, the ‘Remove APIKey QP’ policy simply removes the ‘apikey’ query parameter from the HTTP request message attached to the flow so it is not sent to the backend service. In this scenario we are removing the ‘apikey’ immediately after verify API Key policy, but depending on your use case, removing the ‘apikey’ may need to be done at a later stage in the flow.
- Testing the API Key Verification Policy
Until now anyone with the URL to the ‘{your_initials}_hotel’ API Proxy has been able to make a request with appropriate parameters and get a response back. Now that you have added the API Key Verification policy, that will no longer be the case.
a. Start the Trace session for the ‘{your_initials}_hotels’ proxy
b. Now that the API Key Verification policy has been added to the proxy, try and send a test ‘/GET hotels’ request from Postman with the following query parameters: zipcode=98101&radius=200.
Note : Replace the URL of hotels API with {your_initials}_hotels
a. You will notice that the following fault is returned since an API Key has not been provided as a request query parameter:
{
fault: {
faultstring: "Failed to resolve API Key variable request.queryparam.apikey",
detail: {
errorcode: "steps.oauth.v2.FailedToResolveAPIKey"
}
}
}
The above response shows that the API Key Verification policy is being enforced as expected.
a. Review the Trace for the proxy and the returned response to ensure that the flow is working as expected.
b. Stop the Trace session for the proxy
- **Obtaining an API Key **
Up to now you have been playing the role of an API Developer configuring various policies in your proxy.
To understand the concept of an API Key and associated concepts such as API Products, Developer and Developer Apps, you need to now think about the role of an App Developer. This Developer needs an API Key that can be used whenever their app needs to use the proxy.
To make it easier for Developers to consume APIs, Apigee Edge provides the capability of publishing APIs. Publishing is the process of making your APIs available to Developers for consumption. Publishing APIs can be broadly defined by the following tasks:
-
Create the API Products on Apigee Edge that bundle your APIs.
-
Register Developers on Edge. Only a registered App Developer can register an App.
-
Developers register Developer Apps on Edge to access API products. In response, the developer receives an API key. Now that the developer has an API key, they can make requests to your APIs.
For more, see Publishing Overview.
The following table defines some of the terms used to register apps and generate keys:
Term Definition API product 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. For more, see API Products Developer The API consumer. Developers write apps the make requests to your APIs. For more, see Developer App A client-side app that a developer registers to access an API product. Registering the app with the API product generates the API key for accessing the APIs in that product. API key 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.
With the above brief introduction to API Products, Developers and Developer Apps, you will now create one of each to obtain a valid API Key that can be used to call your proxy
a. Publishing an API Product
i. From the Apigee Edge Management UI, go to Publish → API Products
ii. Click on ‘+ Product’ button to add a new product
iii. In the ‘Product Details’ section of the new product screen,
enter or select the following values for the various fields:
- Display Name: **{Your\_Initials}\_Hospitality Basic Product
**
- Description: **API Bundle for a basic Hospitality App.**
- Environment: **Test**
- Access: **Public**
- Key Approval Type: **Automatic**
i. In the ‘Resources’ section select the following values for the various fields:
- API Proxy: **{your\_initial}\_hotels **
- Revision: **1**
- Resource Path: **/**
i. Click on ‘Import Resources’ to add the ‘/’ resource of your proxy to the API product
ii. Repeat the above two steps for the ‘/**’ resource
iii. Click ‘Save’ to save the API Product. The new product should now be listed on the ‘Products’ page.
a. Registering a Developer
Developers access your APIs through apps. When the developer registers an app, they receive a single API key that allows them to access all of the API products associated with the app. However, developers must be registered before they can register an app.
Developers typically have several ways of registering:
- If you have a paid Edge account, through a Developer Services portal. See Add and manage user accounts for more.
-
By accessing a form that uses the Edge management API to register the developer. See Using the Edge management API to Publish APIs for more.
-
By a back-end administrator using the Edge management UI.
You will be learning more about how Developers can go through a self-service registration process using Developer Services Portal in later lessons. For the continuity of this lesson, the following steps describe the process of registering Developers and Developer Apps using the Apigee Edge Management UI.
i. From the Apigee Edge Management UI, go to Publish → Developers
ii. Click on ‘+ Developer’ button to add a new developer
iii. Add a new developer with the following properties:
- First Name: **Your First Name **
- Last Name: **Your Last Name **
- Email: **{your email\_id}**
- Username: **{firstname\_lastname}**
i. Click ‘Save’ to save the Developer. The new developer should now be listed on the ‘Developer’ page.
a. Registering a Developer App
Now that you have an API product and a developer, you can register a Developer App with the API product. Registering the Developer App generates the API key for the API products associated with the app. You can then distribute the key to app developers so they can access the features in the API products from the app.
As mentioned earlier, you will learn about self-registering apps as a developer using Developer Services Portal in later lessons. For the continuity of this lesson, the following steps describe the process of registering Developer Apps using the Apigee Edge Management UI.
i. From the Apigee Edge Management UI, go to Publish → Developer Apps
ii. Click on ‘+ Developer App’ button to add a new product
iii. In the ‘Developer App Details’ section, enter or select the following values for the various fields:
- Display Name: **{Your\_Initials}\_iExplore App**
- Developer: **{Your\_name}**
- Callback URL: **Leave it blank**
iv. In the ‘Products’ section, click on the ‘+ Product’ button
v. From the ‘Product’ drop-down, select the product you created.
vi. Click the ‘check-mark’ button in the ‘Actions’ column to accept the changes
i. Click ‘Save’ to save the Developer App. The new app should now be listed on the ‘Developer Apps’ page
ii. From the ‘Developer Apps’ page, select your App.
iii. In the ‘Products’ section, next to the entry for ‘{Your_Initials}_Hospitality Basic Product,’ click ‘Show’ in the ‘Consumer Key’ and ‘Consumer Secret’ columns to display the generated keys
Note: Since you selected ‘Key Approval Type: Automatic’ when you created the API product, 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 to approve the API key.
The way your proxy is configured, as of now, the Consumer Key (i.e. the API Key) is the only key that the your App will need to access the proxy resources. You will use the Consumer Secret (i.e. the API Secret) in the next section when the security policy is changed from API Key Verification to an OAuth Token Validation policy.
- Re-testing the API Key Verification Policy
Now that you have a valid API Key associated with a Developer App with access to the API Product that bundles your API proxy, test the API Key Verification policy to ensure that everything works as expected.
a. Copy the ‘Consumer Key’ associated with the app by going to Publish → Developer Apps → {Your_Initials}_iExplore App
b. Start the Trace session for the ‘{Your_Initials}_hotels’ proxy
c. Send a test ‘/GET hotels’ request from Postman with the following query parameters: zipcode=98101&radius=200&apikey={Your_Initials}_iExplore App Consumer Key
Note: Replace the API proxy name with {your_initial}_hotels. Also replace the {Your_Initials}_iExplore App Consumer Key with the actual Consumer Key. As you copy-paste, be sure to remove any spaces before and after the Consumer Key
a. Review the Trace for the proxy and the returned response to ensure that the flow is working as expected.
b. Stop the Trace session for the ‘{Your_Initials}_hotels’ proxy
- Stepping-up security using OAuth 2.0: Client Credentials Grant
For convenience, all organizations on Apigee Edge come preconfigured with a set of OAuth 2.0 endpoints that implement the ‘client credentials grant type’. For information about the configuration of the default ‘oauth’ proxy, review policies in the oauth token endpoint.
This section of the lesson explains how to protect an API using this default ‘oauth’ proxy configuration.
About 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 the consumer key and secret pair that Apigee Edge issues for each app that is registered in an organization.
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.
Client credentials has very specific use cases, and is not the grant type most commonly used for web and mobile apps. For a general introduction to OAuth 2.0 grant types with definitions and use cases, see Introduction to OAuth 2.0.
To support use cases with grant types other than client credentials, the OAuth proxy must be configured with authorization endpoints. For additional information, see configuring authorization endpoints and authorizing requests using OAuth 2.0.
a. **Adding an OAuth 2.0 Token Validation Policy **
i. Go to the Apigee Edge Management UI browser tab
ii. Since you will be adding an OAuth v2.0 policy, the API Key
Verification policy is no longer necessary. Delete the ‘Verify
API Key’ policy from the ‘{your\_initials}\_hotels’ proxy
default proxy endpoint preflow.
i. Similarly remove “Remove-APIKey-QP” policy as well since we no longer need it.
ii. Using the ‘New Policy’ drop-down from the ‘Develop’ tab of the ‘{your_initials}_hotels’ proxy, add the ‘OAuth v2.0’ policy with the following properties:
- Policy Display Name: **Validate OAuth v2 Token**
- Policy Name: **Validate-OAuth-v2-Token**
- Attach Policy: **Checked**
- Flow: **Flow PreFlow, Proxy Endpoint default**
- Segment: **Request**
iii. The ‘Validate OAuth v2 Token’ policy will get added after the ‘Response Cache’ policy. Drag and move the ‘Validate OAuth v2 Token’ policy to be before the ‘Spike Arrest” policy.
i. Review the XML configuration and/or the properties associated with the ‘Validate OAuth v2 Token’ policy.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OAuthV2 async="false" continueOnError="false" enabled="true" name="Validate-OAuth-v2-Token">
<DisplayName>Validate OAuth v2 Token</DisplayName>
<FaultRules/>
<Properties/>
<Attributes/>
<ExternalAuthorization>false</ExternalAuthorization>
<Operation>VerifyAccessToken</Operation>
<SupportedGrantTypes/>
<GenerateResponse enabled="true"/>
<Tokens/>
</OAuthV2>
(You can find the policy xml here. Click the “Raw” button and copy/paste into your policy editor).
The value of the <Operation> element indicates the action to take - in this case, verification of the access token.
The value of the <ExternalAuthorization> element is set to ‘false,’ indicating that Apigee Edge should validate the OAuth Token rather than delegating it to an external validator.
a. **Removing the Authorization Header After Validating the OAuth Token **
i. Using the ‘New Policy’ drop-down from the ‘Design’ tab of the
‘{your\_initials}\_hotels’ proxy, add the ‘Assign Message’
policy with the following properties:
- Policy Display Name:**Remove Authorization Header **
- Policy Name: **Remove-Authorization-Header**
- Attach Policy: **Checked**
- Flow: **Flow PreFlow, Proxy Endpoint default**
- Segment: **Request**
ii. The ‘Remove Authorization Header’ policy will get added after
the ‘Response Cache’ policy. **Drag and move** the ‘Remove
Authorization Header’ policy to be before the ‘Response Cache’
policy
a. For the ‘Remove Authorization Header’ policy, change the XML configuration of the policy using the ‘Code: Remove Authorization Header’ panel as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Remove-Authorization-Header">
<DisplayName>Remove Authorization Header</DisplayName>
<Remove>
<Headers>
<Header name="Authorization"></Header>
</Headers>
</Remove>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
(You can find the policy xml here. Click the “Raw” button and copy/paste into your policy editor).
As a security measure, the ‘Remove Authorization Header’ policy removes the ‘Authorization’ header from the HTTP request message so it is not sent to the backend service. In fact, if the ‘Authorization’ header is not removed, the Backend-as-a-Service API will throw an invalid token error.
Note : You could also have this functionality as part of the “Remove APIKey QP” policy.
a. Testing the OAuth 2.0 Token Validation Policy without a Token
i. Copy the ‘Consumer Key’ associated with the
‘{your\_initials}\_iExplore App’ by going to Publish → Developer
Apps → {your\_initials}\_iExplore App
ii. Start a Trace session for the ‘{your\_initials}\_hotels’ proxy
iii. Send a test ‘/GET hotels’ request from Postman with the
following query parameters:
zipcode=98101&radius=200&apikey=**{Your\_Initials}\_iExplore App
Consumer Key.**
Note :
Replace ‘hotels’ API proxy to point to {your_initials}_hotel
i. As expected, a fault will be returned since a valid OAuth Token has not been provided as part of the request:
{
fault: {
faultstring: "Invalid access token",
detail: {
errorcode: "oauth.v2.InvalidAccessToken"
}
}
}
The above response shows that the API Key Verification policy is being enforced as expected.
i. Review the Trace for the proxy and the returned response to ensure that the flow is working as expected.
ii. Stop the Trace session for the ‘{your_initials}_hotels’ proxy
a. Testing the OAuth 2.0 Token Validation Policy with a Valid Token
i. You will obtain a valid oauth token by directly calling the
’oauth’ API proxy token endpoint and passing the consumer key
and consumer secret of the ‘{your\_initials}\_iExplore App’ app.
ii. Send a test ‘/POST OAuth Token - Client Cred’ request from
Postman after setting appropriate values in the
‘x-www-form-urlencoded’ section of the request:
- client\_id: **{your\_initials}\_iExplore App Consumer Key**
- client\_secret: **{your\_initials}\_iExplore App Consumer
Secret**
- grant\_type: **client\_credentials (this should be added as
query param)**
Note: Copy-paste the Consumer Key and Consumer Secret from the {your_initials}_iExplore App’s detail page. As you copy-paste, remove any spaces before and after the values of the Consumer Key and Consumer Secret.
i. Review the response of the ‘/POST OAuth Token - Client Cred’ request. Copy the value of the ‘access_token’ attribute to use in the next step.
{
issued_at: "1414962637000",
application_name: "ef723b8b-fdb1-4aae-9418-096d8ab7fec7",
scope: "",
status: "approved",
api_product_list: "[Hospitality]",
expires_in: "3599",
developer.email: "[email protected]",
organization_id: "0",
token_type: "BearerToken",
client_id: "P24PNGrXN0gTNdVi6giT12Dq0vrG3ruB",
access_token: "**j1AA2PeAtKOMCZa9tuCdDDsRqn8J**",
organization_name: "demo37",
refresh_token_expires_in: "0",
refresh_count: "0"
}
i. Start a Trace session for the ‘{your_initials}_hotels’ proxy
ii. Set up the ‘/GET hotels’ request in Postman with the following query parameters AND header:
-
Query Parameters:
-
zipcode: 98101
-
radius: 200
-
-
Header:
-
Add Authorization*: Bearer {access_token}***
-
Remove the content type header “application/json” (if there is one)
-
Note:
-
Replace the API proxy URL with {your_initials}_hotels URL.
-
Replace the {access_token} with the value of the ‘access_token’ from the response in the step above.
i. Send the Postman request.
ii. Review the Trace for the proxy and the returned response to ensure that the flow is working as expected.
iii. Stop the Trace session for the ‘{your_initials}_hotels’ proxy
Summary
That completes this hands-on lesson. In this lesson you learned about the various out-of-the-box security related policies that are available in Apigee Edge and to leverage a couple of those policies - API Key Verification and OAuth 2.0 client credentials grant - to secure your APIs.
Now go to Lab 7.