Skip to content
This repository has been archived by the owner on Jul 14, 2022. It is now read-only.

Quick Start: Add Apigee OAuth

Developerdave edited this page Mar 27, 2015 · 56 revisions

#Adding Apigee OAuth 2.0 to the API

This topic shows you how to add basic OAuth 2.0 security to the "quick start" example API.

What you need to know about this example

There are really three parts to this example:

  • The first is adding OAuth 2.0 security to an API. You do this by configuring custom resources in the Swagger file.

  • The second part is calling an OAuth endpoint to retrieve an access token. In this example, the endpoint is deployed on Apigee Edge. However, you could also use a local Redis implementation.

  • The third is using the access token to call the secure API.

In this scenario, Apigee Edge is the authorization server (as defined in the IETF OAuth 2.0 Authorization Framework spec.) This means that Apigee-127 will call endpoints on Apigee Edge to obtain access tokens, authorization tokens, and refresh tokens.

Before you begin

To use Apigee Edge as the OAuth 2.0 authorization server, you need to create an Apigee-127 account with your Apigee account information. If you already created an Apigee-127 account, you can skip these steps. To verify that you have an active account, execute a127 account list.

  1. Execute a127 account create <account-name>.
  2. Follow the prompts to create an Apigee-127 account using Apigee as the account provider.

Note: Be sure to select apigee as the provider.

a127 account create my-account

    [?] Provider? 
      amazon 
    ❯ apigee 
      local
    ...

Note: If you do not have an account on Apigee Edge, you'll be prompted to create one.

For more details on account creation, see the Apigee-127 Command-Line Reference.

Adding OAuth 2.0 security to the API

Now, let's add OAuth security to the API. Most of the configuration work is done right in the Swagger editor with Volos.js extensions.

  1. Create and test the "quick start" sample API, as explained in "Quick start.

  2. Be sure you have created an Apigee-127 account with your Apigee account information, as explained in the previous section.

    Note: Make sure that your project's package.json file includes volos-oauth-apigee module in the dependencies list. If you're using the default skeleton project, you don't need to do anything -- the module is already included in package.json.

  3. Create a RemoteProxy service and bind it to your project, as explained in "Understanding remote services".

  4. Open the Swagger editor: a127 project edit.

  5. Look for these lines:

  x-a127-config: {}
  x-a127-services: {}
  1. Replace those lines with the following stanzas.

    Important: Add these stanzas exactly as shown. These are top-level tags -- the extension names should be indented all the way to the left.

x-a127-config:
  ##
  ## Note: For <RemoteProxyName> below, substitute the name of the 
  ## remote proxy service you created previously. For example:
  ## MyRemoteProxyService.key: &apigeeProxyKey CONFIGURED
  ##
  <RemoteProxyName>.key: &apigeeProxyKey CONFIGURED
  <RemoteProxyName>.uri: &apigeeProxyUri CONFIGURED
x-a127-services:
  oauth2:
    provider: volos-oauth-apigee
    options:
      tokenLifetime: 300000
      key: *apigeeProxyKey
      uri: *apigeeProxyUri
      #cache: mycache (See Oauth options section below.)
      validGrantTypes:
        - client_credentials
        - authorization_code
        - implicit_grant
        - password
      tokenPaths:  # These will be added to your paths section for you
        authorize: /authorize
        token: /accesstoken
        invalidate: /invalidate
        refresh: /refresh
  1. Add x-www-form-urlencoded to the "consumes" part of the spec, like this:

      consumes:
        - application/json
        - application/x-www-form-urlencoded
  2. Add the Swagger security schema definition to the YAML, as follows. You can add it to the end of the file, after the definitions section. For details on the security schema settings, see Security scheme settings.

    securityDefinitions:
      oauth2:
        type: oauth2
        scopes:
          read: "allow read"
        flow: application
        tokenUrl: ignored
  3. Apply the oauth2 security key to the get operation of the /hello path, as follows:

    paths:
      /hello:
         # binds a127 app logic to a route
         x-swagger-router-controller: hello_world
         x-a127-apply: {}
         get:
           description: Returns 'Hello' to the caller
           # used as the method name of the controller
           operationId: hello
           security:
           - oauth2: []
    

Deprecation notice: You can also apply an oauth2 authorization using the x-a127-authorizations extension, as shown below. However, note that this extension is deprecated. Please apply OAuth security using the security element, as shown in the previous step.

  /hello:
    x-swagger-router-controller: hello
    x-a127-authorizations:
      oauth2: {}

That's it! You've secured your API. Without a valid access token, any request to the API will fail. Now, you need to go through a few steps to obtain an access token and test your API. We'll walk through these steps next.

Verifying the configuration

To test the OAuth configuration, you need to obtain an access token (also called a bearer token) from the Apigee Edge OAuth manager. We'll walk through the steps.

First, verify that the security mechanism is working. Start up the app and try calling it. For example,

  1. a127 project start

  2. curl -i http://localhost:10010/hello?name=Scott

        {"error_description":"Missing Authorization header","error":"missing_authorization"}

If you added OAuth correctly, the request is rejected because you need to obtain and present an access token in the request header.

Obtaining the client credentials

One way to get a useable set of client credentials is from the developer app that was created you created the RemoteProxy service. Just log in to Edge and go to Publish > Developer Apps, and look for the app with the same name as the RemoteProxy service you created. Open the app in the UI, and click "Show" to show the Consumer Key and Consumer Secret values.

Another way to get a usable set of client credentials is from the default developer app that is provisioned with each new Apigee Edge organization. Again, you can go to Publish > Developer Apps, and look for the app called "Test App". Click Show to show the Consumer Key and Consumer Secret values.

You can also follow these steps to create a new developer app manually, if you do not wish to use Test App:

  1. Sign in to your Apigee account.
  2. Create a new Product. (Publish > Product and fill in the form. You can leave the API Proxy field blank -- it isn't necessary to select an API proxy for this exercise.)
  3. Create a new Developer. (Publish > Developer and fill out the form).
  4. Create a new Developer App. (Publish > Developer App and fill out the form, and click Save)
  5. Open the Developer App you just created. Click Show next to the Consumer Key and Consumer Secret fields (in the following figure, the keys are shown):

alt text

Configuring the product for your developer app

Important: You must follow the steps described here before you generate an access token. You need to add a "/" resource to the product associated with the developer app where you will obtain the keys to generate an access token.

  1. Log on to the Apigee Edge management UI.
  2. Select Publish > Developer Apps and open the developer app that contains the Consumer Key and Consumer Secret that you intend to use to generate an access token.
  3. Click the link to the product that's associated with the app.
  4. In the Product page, click Edit.
  5. In the Paths section under Resources, click + Custom Resource.
  6. Enter "/" as the custom resource (without quotes).
  7. Click Save.
  8. Now you can generate an access token.

Obtaining an access token

Important: Be sure to follow the steps in "Configuring the product for your developer app" before you generate an access token for your API.

Now, with valid client credentials in hand, you can request an access token from the token endpoint (on Apigee Edge) as follows (substitute the Consumer ID and Consumer secret values you just obtained for the client_id and client_secret parameters):

Note: We're going to specify that we are using the client credentials grant type. This simply means that to obtain an access token, the client has to provide two key pieces of information: the client ID and client secret.

  curl -X POST "http://localhost:10010/accesstoken" -d "grant_type=client_credentials&client_id=o2lxnymziDkjXNgGtb9&client_secret=S9vUARV" | python -m json.tool
  {
      "access_token": "7zSVVqNCsGYQKWDKyXGOTUBA",
      "api_product_list": "[Test App product]",
      "api_profile_name": null,
      "application_name": "921c6d-78c0-4b81-9884-c1f7d7b8f",
      "client_id": "o2lxnymzY9iDkjXb9PsNJCZNJXVP",
      "developer_email": "someperson@example.com",
      "expires_in": 1799,
      "issued_at": 1411398701495,
      "organization_id": "0",
      "organization_name": "wwitman",
      "refresh_count": 0,
      "refresh_token": null,
      "refresh_token_expires_in": 0,
      "refresh_token_status": null,
      "scope": "",
      "state": null,
      "status": "approved",
      "token_type": "bearer"
  }

If everything succeeded, you'll find the access token in the response (sample shown above).

Note: The route for the token endpoint is /accesstoken, which is added by default as one of the tokenPaths in the Swagger file.

Call the secure API

Now, with an access token, you can call the secured /hello API. Be sure to start the project before executing the call: a127 project start.

curl -i "http://localhost:10010/hello?name=Scott" -H "Authorization: Bearer 7zSVVqNCsGYQKWDKyXGOTUBA"

And it returns:

Hello, Scott

If this succeeds, it shows that the access token was accepted, and you've successfully completed the steps for obtaining an access token and securing an API with OAuth 2.0. All through Apigee-127!

Security scheme settings

You configure the Swagger 2.0 security scheme in the securityDefinitions section.

  securityDefinitions:
    oauth2:
      type: oauth2
      scopes:
        read: "allow read"
      flow: application
      tokenUrl: https://example.com/accessToken

The security scheme in this example uses these fields:

  • type - Valid value is oauth2.
  • scopes - The available scopes for the OAuth 2.0 security scheme. The value is the name of the scope, followed by a colon, followed by a brief description.
  • flow - Specifies which OAuth 2.0 grant type you are using. Possible values are:
    • implicit -- Specifies the implicit grant type.
    • password -- Specifies the passwod grant type.
    • application -- Specifies the client credentials grant type.
    • accessCode -- Specifies the authorization code grant type.
  • tokenUrl - Used with the password, application, and accessCode flows. Just specify an arbitrary URL. This value is ignored.

##OAuth 2.0 service options

This section describes the options you can set when you configure an oauth2 provider. For example:

    x-a127-services:
      oauth2:
        provider: volos-oauth-apigee
        options:
          tokenLifetime: 300000
          key: *apigeeProxyKey
          uri: *apigeeProxyUri
          cache: mycache 
          validGrantTypes:
            - client_credentials
            - authorization_code
            - implicit_grant
            - password
          tokenPaths:  # These will be added to your paths section for you
            authorize: /authorize
            token: /accesstoken
            invalidate: /invalidate
            refresh: /refresh
  • tokenLifetime -- Specify the expiration for a token, in milliseconds.

  • key -- A reference to the API key for the remote proxy on Apigee Edge used to create and validate tokens, and perform other functions. This key is set for you automatically when you create a new Apigee-127 account and specify "apigee" as the provider. It is set in the x-a127-config section of the Swagger file.

  • uri -- The base path to the remote proxy deployed to Apigee Edge. Like with "key", this is set when you create a new Apigee-127 account.

  • cache -- Specifies the name of a cache defined in the x-a127-services section of the Swagger file. This cache is used to cache the validation of an access token. This avoids the need to make a call on every API call to validate the token. For example, to define a cache, you do this:

      x-a127-services
        mycache:     
          provider: volos-cache-memory
          options:
            name: hello-cache
            ttl: 60000 
  • validGrantTypes - The OAuth 2.0 grant types that are valid for this API. They include client_credentials, authorization_code, implicit_grant, and password. This setting lets you limit the grant type implementations that the API can use.

  • tokenPaths - The paths used to interact with the authorization server, to request access tokens and authorization tokens, invalidate tokens, and handle refresh tokens.

Clone this wiki locally