Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
code rename Password Grant exercise, and update README Mar 29, 2018
media rename Password Grant exercise, and update README Mar 29, 2018

API Security : Securing APIs with OAuth Password Grant

Duration : 30 mins

Persona : API Team/Security

Use case

You have a set of APIs that are consumed by a trusted app, on behalf of authenticated users. You want to secure those APIs using a two-legged OAuth. In other words, you want your APIs to authenticate the client apps as well as the users.

How can Apigee Edge help?

The OAuth specification defines token endpoints, authorization endpoints, and refresh endpoints. Apps call these endpoints to get access tokens, to refresh access tokens, and to verify tokens.

Apigee Edge quickly lets you secure your APIs using out of the box OAuth policies. Apigee Edge OAuth policies can be used to implement the standard OAuth endpoints, and lets you easily secure your APIs using a simply policy to verify tokens.

Background: What's a token?

An OAuth token is a digital analog of an old-school subway token: it's a "ticket to ride". The holder of an OAuth token (a client application) can present it to the token verifier (typically a gateway or a server application), and if the token is valid, then the token verifier will treat the request as valid.

When you use Apigee Edge OAuth to protect your APIs, Apigee Edge acts as the token issuer and the token verifier. The flow for an app that uses the password grant type (a form of 2-legged OAuth), looks like this:

image alt text

The password grant type is used when the app is trusted, and is performing work on behalf of an authenticated user. The user is the resource owner. For example, an app may need to access a backend cloud-based storage service to store and retrieve items for the authenticated user. Different users might authenticate to the app at different times (and on different devices). Imagine a mobile app that allows customers to place orders. The client credentials grant might be used to protect data that is not customer specific - like a query on the product catalog, or even populating an anonymously-held "shopping cart". The password grant would be used to authenticate requests to create orders on behalf of a specific person.

In the password grant, the app handles user credentials, and therefore must be trusted. The OAuth server verifies the credentials.

When using the password grant type, Apigee Edge is the OAuth authorization server. Its role is to generate access tokens, validate access tokens, and proxy authorized requests for protected resources on to the resource server.



Create the API Proxy

(You can skip this part if you already have a pass-through proxy that verifies OAuth tokens.)

  1. First, download this zip file to your local machine, by clicking the link, and then clicking "Download". Then return here.

  2. Open a browser tab to and be sure you are logged in.

  3. Select Develop → API Proxies in the side navigation menu

    image alt text

  4. Click + Proxy. The Build a Proxy wizard is invoked.

  5. Select Proxy bundle. Click on Next, and then choose the zip file that you just downloaded.

    image alt text

  6. Specify the name for the new proxy, using your initials..., and click Next

    image alt text

  7. Then click Build

    image alt text

  8. Once the API proxy has been built, click the link to view your proxy in the proxy editor.

  9. You should see the proxy Overview screen.

  10. Click the Develop tab.

    image alt text

    This shows you the contents of the API Proxy definition. This is just a pass-through proxy. There are no logic steps on this proxy, yet.

  11. Select the Proxy name and Update the display name with your initials.

    image alt text

  12. Select the Proxy Endpoint and update the basepath, similarly.

    image alt text

  13. Select PreFlow from the sidebar under Proxy Endpoints section.

    image alt text

  14. Click on +Step

    image alt text

  15. In the resulting dialog, scroll down select OAuth v2.0 from the Security section then click the Add button.

    image alt text

  16. Click on the policy and in the code editor, paste the code given below:

    <OAuthV2 name="OAuth-v20-1">
       <DisplayName>OAuth v2.0-1</DisplayName>
       <GenerateResponse enabled="true"/>

    It should look like this:

    image alt text

  17. Because we want Apigee to not pass the token to the backend API, let's remove the Authorization header. To do so, again click on +Step.

  18. In the dialog, select Assign Message policy from the Mediation section then click the Add button.

    image alt text

  19. Click on the policy and in the code editor, paste the code give below

    <AssignMessage name="Assign-Message-1">
      <DisplayName>Assign Message-1</DisplayName>
            <Header name="Authorization"/>
      <AssignTo createNew="false" transport="http" type="request"/>

    It should look like this:

    image alt text

  20. Click the blue Save button to save the proxy.

  21. Congratulations!...You’ve now successfully created an API in Apigee Edge that is protected with OAuth 2.0.

  22. Use the Deployment dropdown to deploy it on the test environment.

    image alt text

Create the API Product

To test the API Proxy, we need to expose that proxy via an API Product, and generate a new developer app. First, the product.

  1. In the Apigee UI, select Publish → API Products from the side navigation menu

    image alt text

  2. Click +API Product

    image alt text

  3. Populate the following fields

    • Section: Product Details

      • Name: {your_initials}_oauth_product

      • Environment: test

      • Access: Public

      • Allowed OAuth Scopes: A,B,C

    • Section: Resources

      • Section: API Proxies

        • Click the +API Proxy button

          image alt text

        • Select the API Proxy you just created.

  4. Click the blue Save button on the bottom right corner of the page, to save the API Product.

    There is now a new, consumable unit of APIs available to external (consuming) developers.

    Side note: What is an OAuth scope? A scope is something you can attach to an OAuth token that stipulates or limits the authorization associated to the token. For example, you could define READ and WRITE scopes on a single resource. Or, you could imagine a 2x2 matrix of {READ,WRITE} and {RESOURCE1,RESOURCE2}. A user may wish to grant READ access to an app (let's say, ability to read a "favorites list"), or WRITE access to the app (eg, ability to update the "favorites list"). For more on OAuth scopes, please see this article.

    Apigee Edge allows you to define any set of scopes that can be attached to a token, and allows users the ability to restrict the set of scopes they grant to an app.

Create the App

  1. Click Publish → Apps in the side navigation

    image alt text

  2. Click +App

    image alt text

  3. Populate the following fields

    • Name: **{your_initials}-oauth-pg-app

    • Developer: (choose any available developer)

    • Product: Click +Product to add your API Product to this App.

    image alt text

  4. In the lower right corner, click the blue Save button.

Get the client credentials

Now, obtain the consumer key and secret for the app, and encode them.

  1. In the apps list, select the app that you just created

  2. Click on the show button under Consumer Key and Consumer Secret.

  3. Copy the values and store them somewhere safe.

  4. To get the encoded value, visit a base64 encoder site, like this one.

    Paste in the value of the consumer key, followed by a colon, followed by the consumer secret. For example if the consumer key is ABCDE and the consumer secret is 12345, you would paste in


    There should be no spaces or newlines.

    Mac and Linux users, you can alternatively do this from the command prompt. Open Terminal and type the following command:

     printf ABCDE:12345 | base64

    ...obviously replacing the value of your consumer key and secret as approprpiate.

    Windows users, you can alternatively use Powershell:

    PS> $b = [System.Text.Encoding]::UTF8.GetBytes("ABCDE:12345")
    PS> [System.Convert]::ToBase64String($b)

    Again, substitute your client id and secret appropriately.

  5. Save the resulting base64-encoded value. It will look something like this:


Test the app

Now, let’s test the deployment using the Apigee REST Client. (You can also use Postman or Paw or any other rest client tool that you know)

  1. In the Apigee UI, Navigate to Develop...Proxies...

  2. Select the API Proxy called "oauth2-cc" or similar. This is a proxy that was previously configured for you. Everyone will use this same proxy. (This is not a proxy you built today).

  3. From the Proxy overview panel, copy the URL for your OAuth API proxy.

    image alt text

    The url should end with oauth2-pg; we use cc here to imply password grant.

  4. Open the Apigee REST Client in a new browser window.

  5. Obtain an access token. Specify these settings:

    • url endpoint:
    • method: POST
    • Body: parameter: grant_type value: password
    • Body: parameter: username value:
    • Body: parameter: password value: Relativity
    • Header: Authorization: Basic **{base64 encoded client credentials value}**

    You can find other valid username / password pairs by visiting:

    For the value in the header, use the base64 encoded value of consumer key and secret pair that you obtained previously.

    image alt text

  6. Click Send and you should see a response like this below. Then, copy the value for access token.

    image alt text

  7. Now, you should be able to get the employees list using the access token that we just obtained. Copy the URL for the OAuth protected proxy you created earlier in this lab.

    image alt text

  8. Paste the URL in the REST client, add the Authorization header and send a GET request . The value for Authorization header will be the word "Bearer" followed by the access token that we obtained previously.

    Authorization: Bearer {access_token}

    image alt text

  9. Hit Send and you should see a response like this below.

    image alt text

  10. If you alter the token in the Authorization header (remove a character) and then send another request, you will see a 401 Unauthorized, and a "Invalid Access Token" message.

  11. If you remove the Authorization header and send another request, you will see a similar 401 Unauthorized error.

Lab Video

If you don’t want to implement this use case, you can watch this short video to see how to implement Password grant 2-legged OAuth on Apigee Edge.

Earn Extra-points

Now that you’ve learned how to secure your API with OAuth 2.0, try to control the expiry of the access token that is generated.

For Discussion

  1. What are the various OAuth 2.0 grant types supported by Apigee Edge?

  2. What are the various operations that are provided by the OAuth v2.0 policy?

  3. Suppose an app has a token obtained via a client_credentials grant; what does the token authenticate?

  4. How would you go about getting a token that authenticated the end user?


In this lab you learned how to secure your API using a two legged OAuth by using the default oauth proxy obtaining an access code and using that against your API.


Rate this Exercise

How did you like this exercise? Rate here.

You can’t perform that action at this time.