API Management with Red Hat 3scale API Management Platform

Reference Architectures 2017

Abstract

This reference architecture will demonstrate 3scale API Management Platform on-premises installation using API gatway secure JBoss Fuse API on Openshift.

Comments and Feedback

In the spirit of open source, we invite anyone to provide feedback and comments on any reference architecture. Although we review our papers internally, sometimes issues or typographical errors are encountered. Feedback allows us to not only improve the quality of the papers we produce, but allows the reader to provide their thoughts on potential improvements and topic expansion to the papers. Feedback on the papers can be provided by emailing refarch-feedback@redhat.com. Please refer to the title within the email.

Chapter 1. Executive Summary

APIs are the building blocks of the digital economy. Because they are key to seizing business value, you need a world-class API infrastructure that delivers now and into the future.

Red Hat® 3scale API Management Platform makes it easy to manage your APIs for internal or external users. Share, secure, distribute, control, and monetize your APIs on an infrastructure platform built with performance, customer control, and future growth in mind. And now, with the release of 3scale API Management Platform 2, you can place any 3scale components on-premise, in the cloud, or on any combination of the two.

Refer to the official Red Hat documentation for more introduction on API use cases.

This reference architecture describes the on-premise installation of Red Hat 3scale API Management Platform on OpenShift Container Platform and demonstrates important capabilities of the product by enhancing the functionality of an existing E-Commerce application through the introduction of an API gateway.

Chapter 2. Reference Architecture Environment

This reference architecture relies on a previous reference architecture application and environment thoroughly described in the paper titled Building Microservices on OpenShift Container Platform with Fuse Integration Services.

This environment installs Red Hat 3scale API Management Platform on OpenShift Container Platform and uses 3scale API Management Platform’s functions to control access to the Fuse gateway service, set rate limits on certain service calls, develop ActiveDocs from the swagger file and display them on Developer Portal of 3scale API Management Platform. A separately deployed Presentation application on OpenShift is used to make various calls to the Fuse gateway service service through 3scale API Management Platform and demonstrate the end to end integration.

The configuration of 3scale API Management Platform for this reference architecture includes creating three APIs in the Admin Portal, based on the Fuse gateway service. These three APIs will be used by three different type of users:

  • Internal user: Access to every API exposed by Fuse gateway service, including product, sales, billing and fulfillment.
  • Partner user (third party): Access is limited to only product calls, and exclusively to inquiry, add, delete and update of products.
  • Public user: Access is limited to only product inquiry, and further limited to just 5 HTTP GET requests per minute
general diagram

OpenShift Container Platform may be deployed with either a single, or three master hosts for this reference architecture. In both cases, it is assumed that ocp-master1 refers to one (or the only) OpenShift master host and that the environment includes two OpenShift node hosts with the host names of ocp-node1 and ocp-node2.

It is further assumed that OpenShift has been installed by the root user and that a regular user has been created with basic access to the host machine, as well as access to OpenShift through its identity providers.

Chapter 3. Install guide

3.1. OpenShift Login

Log in to the master host machine as the regular user, and use the oc utility to authenticate against OpenShift:

$ oc login -u ocuser --certificate-authority=/etc/origin/master/ca.crt --server=https://apimgmt-master.apimgmt.example.com:8443
Authentication required for https://apimgmt-master.apimgmt.example.com:8443 (openshift)
Username: ocuser
Password: PASSWORD
Login successful.

Welcome! See 'oc help' to get started.

3.2. On-premise Installation

Please follow the On-premises Installation Guide to install 3scale API Management Platform (AMP) 2.0 on OpenShift

Create a new project called 3scale-api.

oc new-project 3scale-api --display-name="3scale APM on OpenShift" --description="This project demonstrates the use of 3scale APM on OpenShift"

Next, download amp.yml and proceed with the installation. In the OpenShift environment used for this reference architecture, the wildcard domain is set up as apimgmt.example.com.

oc new-app --file amp.yml --param WILDCARD_DOMAIN=apimgmt.example.com

--> Deploying template "3scale-api/system" for "amp.yml" to project 3scale-api

     system
     ---------
     Login on https://3scale-admin.apimgmt.example.com as admin/bptp5gec


     * With parameters:
        * AMP_RELEASE=2.0.0-CR2-redhat-1
        * ADMIN_PASSWORD=bptp5gec # generated
        * ADMIN_USERNAME=admin
        * APICAST_ACCESS_TOKEN=sjvkpnun # generated
        * ADMIN_ACCESS_TOKEN=kc2tdwob1wijaori # generated
        * WILDCARD_DOMAIN=apimgmt.example.com
        * TENANT_NAME=3scale
        * MySQL User=mysql
        * MySQL Password=ovixy777 # generated
        * MySQL Database Name=system
        * MySQL Root password.=hclunkck # generated
        * SYSTEM_BACKEND_USERNAME=3scale_api_user
        * SYSTEM_BACKEND_PASSWORD=ogboxf8d # generated
        * REDIS_IMAGE=rhscl/redis-32-rhel7:3.2-5.7
        * MYSQL_IMAGE=rhscl/mysql-56-rhel7:5.6-13.14
        * SYSTEM_BACKEND_SHARED_SECRET=sip7ekg4 # generated
        * SYSTEM_APP_SECRET_KEY_BASE=b0b2ec645aa60c2d47bebc817dada0dba73ea5183401185e0060728e7e0c4aa52adb72a112cca22568084b502c2212dc78b8e213187dabeb747a0d55c8ec5c87 # generated
        * APICAST_MANAGEMENT_API=status
        * APICAST_OPENSSL_VERIFY=false
        * APICAST_RESPONSE_CODES=true

--> Creating resources ...
    persistentvolumeclaim "system-storage" created
    persistentvolumeclaim "mysql-storage" created
    persistentvolumeclaim "system-redis-storage" created
    persistentvolumeclaim "backend-redis-storage" created
    deploymentconfig "backend-cron" created
    deploymentconfig "backend-redis" created
    deploymentconfig "backend-listener" created
    service "backend-redis" created
    service "backend-listener" created
    service "system-provider" created
    service "system-developer" created
    deploymentconfig "backend-worker" created
    service "system-mysql" created
    service "system-redis" created
    deploymentconfig "system-redis" created
    service "system-sphinx" created
    deploymentconfig "system-sphinx" created
    service "system-memcache" created
    deploymentconfig "system-memcache" created
    route "system-provider-admin-route" created
    route "backend-route" created
    route "system-developer-route" created
    deploymentconfig "apicast-staging" created
    service "apicast-staging" created
    deploymentconfig "apicast-production" created
    service "apicast-production" created
    route "api-apicast-staging-route" created
    route "api-apicast-production-route" created
    deploymentconfig "system-app" created
    deploymentconfig "system-resque" created
    deploymentconfig "system-sidekiq" created
    deploymentconfig "system-mysql" created
    configmap "redis-config" created
    configmap "smtp" created
--> Success
    Run 'oc status' to view your app.

Please record the username (admin) and password, as these will later be used to log in into 3scale API Management Platform Admin Portal.

Below are the commands to reset and clean up, if you ever need to do a re-installation of the 3scale-api project.

oc delete all --all
oc delete configmap redis-config smtp
oc delete pvc system-storage mysql-storage system-redis-storage backend-redis-storage

3.3. E-Commerce Services

3.3.1. Create Project

Create the new project which will house the E-Commerce Services:

oc new-project ecom-services --display-name="E-Commerce Services Suite" --description="Back-end logic microservice suite"

3.3.2. Template Population

Within the new project, execute the provided YAML template to configure and instantiate the full services suite:

oc new-app -f https://raw.githubusercontent.com/RHsyseng/3scale-apm/master/ecom-svcs/project-template.yaml

3.3.3. Persistence Data Population

Once all services are deployed and running, instantiate the e-commerce data set via a GET request to the gateway service route:

$ curl -i http://ecom.rhmap.example.com/demo/testApi
HTTP/1.1 200 OK
...

3.3.4. Set Secret Token

Then use the following command to set the Secret Token for the gateway service.

oc env dc/gateway-service -e GATEWAY_TOKEN_VALUE=Shared_secret_sent_from_proxy_to_API_backend_12345678987654321

3.4. Log in to 3scale AMP Admin Portal

The console URL, username and the generated password are logged during the processing of the application template by OpenShift. Use this information to log in to the 3scale AMP console.

Login on https://3scale-admin.apimgmt.example.com as admin/bptp5gec

3.5. Create new ActiveDocs

ActiveDocs make API documentation user friendly, interactive, intuitive, and clear. With 3scale ActiveDocs, based on the Swagger Framework, developers can explore APIs live, straight from the documentation web pages.

To take advantage of this feature, it is best to set up ActiveDocs before further defining the API. Click on top menu item called API, then select ActiveDocs to bring up the ActiveDocs page. There is one demo service spec, called Echo, already defined.

ActiveDoc

Click the link to Create a new spec:

ActiveDoc

After filling out all the required fields and clicking the Update Service button, the exposed services can be viewed and tested on the next preview screen:

ActiveDoc

Click on each service to reveal details, including the schema and/or model for the request and response, and the newly added user_key, used for 3scale API Management Platform’s authentication.

ActiveDoc

Use the following values to create three sets of ActiveDocs. For API JSON Spec content, use the corresponding swagger files from the github repository:

Service 1:

Name:           Fuse-gateway-internal
System Name:    Fuse-gateway-internal

Service 2:

Name:           Fuse-gateway-partner
System Name:    Fuse-gateway-partner

Service 3:

Name:           Fuse-gateway-public
System Name:    Fuse-gateway-public

3.6. Configure new APIs

3.6.1. Create new APIs

Used the defined ActiveDocs as references for creating services. Click on the APIs menu, and then click on Create Service.

Figure 3.1. Create Service

create new service

Enter Name and System Name, then press the Create Service button. For this reference architecture, the default configuration is valid; keep using APIcast as the gateway choice and API Key (user_key) as the authentication option.

create new service
create new service
create new service

Create three services as follows:

create new service

Use the following values:

Service 1:

Name: Fuse-gateway-internal
System Name: Fuse-gateway-internal

Service 2:

Name: Fuse-gateway-partner
System Name: Fuse-gateway-partner

Service 3:

Name: Fuse-gateway-public
System Name: Fuse-gateway-public

3.6.1.1. Add methods

The next step is to add methods for the newly added APIs. Click on the Definition link.

API-integration

The methods are defined in the Definition page, click on the New method link.

API-integration

Enter appropriate values for Friendly name and System name.

API-integration

Based on the Fuse gateway service ActiveDocs, create the following methods for these three APIs:

Fuse-gateway-internal API, no limit, with access to all services:

API-integration

Fuse-gateway-partner API, limited to only to the product service:

API-integration

Fuse-gateway-public API, limited to only quries to the product service:

API-integration

3.6.2. Delete default API

Red Hat 3scale API Management Platform installation configures a default API called echo; delete this default API to make future configuration steps more clear, otherwise all new accounts created will automatically point to the default API’s application plan.

  • Click on the APIs menu and then click the API Definition link:
API-delete-default-api
  • On the next screen, click the edit link:
API-delete-default-api
  • Confirm by clicking the link that says I understand the consequences, proceed to delete 'API' service.
API-delete-default-api

3.6.3. Set up integration

Click on the APIs menu, and then click on Integration for each of the new services.

API-integration

On the integration screen, click the button to add the base URL.

API-integration

On this setup page, there are three base URLs:

API-integration

Staging Public Base URL and Production Public Base URL are two important values that need to be recorded; these two addresses have to be added to the 3scale-api project’s router in order for requests from clients to reach OpenShift’s 3scale API gateway staging and production pod.

po/apicast-production-1-3zv6c   1/1       Running   4          3d
po/apicast-staging-1-9kf20      1/1       Running   0          3d

3.6.3.1. Create routes in OpenShift

Use the route option of the oc utility to create all three routes for staging. Setting up the routes for production follows the same pattern.

oc expose service apicast-staging --hostname=fuse-gateway-public-3scale-apicast-staging.apimgmt.example.com --name=fuse-gateway-staging-public-route

oc expose service apicast-staging --hostname=fuse-gateway-partner-3scale-apicast-staging.apimgmt.example.com --name=fuse-gateway-staging-partner-route

oc expose service apicast-staging --hostname=fuse-gateway-internal-3scale-apicast-staging.apimgmt.example.com --name=fuse-gateway-staging-internal-route

Edit each new route to secure it:

oc edit route/fuse-gateway-staging-public-route

oc edit route/fuse-gateway-staging-partner-route

oc edit route/fuse-gateway-staging-internal-route

This is done by adding two lines to the spec that defines the TLS requirement:

spec:
  host: deploy.example.com
  port:
    targetPort: gateway
 tls: termination: edge
  to:
    kind: Service
    name: apicast-staging
    weight: 100
  wildcardPolicy: None

To avoid creating one route for each service, check out the option to Configure Wildcard Domains. This feature is currently in tech preview and does not have full support yet.

3.6.3.2. Private Base URL

The Private Base URL is the address of the Fuse gateway service. Use CLI commands to get the IP address and port of the OpenShift service:

[czhu@apimgmt-master ~]$ oc projects
You have access to the following projects and can switch between them with 'oc project <projectname>':

  * 3scale-api
    default
    ecom-services
    kube-system
    lambdaair
    management-infra
    openshift
    openshift-infra

Using project "3scale-api" on server "https://apimgmt-master.apimgmt.example.com:8443".

[czhu@apimgmt-master ~]$ oc get svc -n ecom-services
NAME                 CLUSTER-IP       EXTERNAL-IP                   PORT(S)             AGE
.......
gateway-service      172.30.124.155   <none>                        8778/TCP,9091/TCP   2d
.......

In our reference environment, http://172.30.124.155:9091 is the address of the service and this value can be used as Private Base URL for all three new APIs, since they all point to the same Fuse gateway service.

3.6.3.3. Create Application Plans

Click on the APIs menu, and then click on Create Application Plan for each of the services.

API-create-application-plan
API-create-application-plan

Use the following values to add four plans, including two plans for the Fuse-gateway-internal API:

Name:           desktop-plan
System Name:    desktop-plan
Name:           mobile-plan
System Name:    mobile-plan

One plan for the Fuse-gateway-partner API:

Name:           partner-plan
System Name:    partner-plan

One plan for the Fuse-gateway-public API:

Name:           public-plan
System Name:    public-plan

Also select a Default Plan for APIs. For example, two plans are defined for the Fuse-gateway-internal API. Select desktop-plan as the Default Plan, so that new applications created from this point on, automatically associate with the desktop-plan for this API.

API-create-application-plan

3.6.3.4. Add mapping rules

Next, click the Add a mapping rule link to go to Integration page and add new mapping rules for the methods. This step is quite straight forward; just repeat it for all three APIs.

API-integration

3.6.3.5. Set up rate limits for public plan

Set up Rate Limits for the public plan, so that anonymous public requests will not overload the infrastructure capacity. Click on Fuse-gateway-public API’s Application Plans link.

API-limit

Then click on New usage limit for the product-get method and add a Usage limit. For example, set a maximum rate of 5 calls per minute:

API-limit

3.7. Create new Accounts

Click on the top menu item, titled Developers.

A default developer by the name of John Doe has been created during installation; it is best to remove this developer to avoid future confusion.

Account-create-new-accounts

Click on the Create link to navigate to the Create new Account page.

Account-create-new-accounts

With each new user, should an existing API with an application plan exist, the system will create an application to point to them. The created application will select the first available API plan by default, which may not be appropriate, unless a Default Plan is already chosen for the API. Review the corresponding screen and create the needed applications, once the right APIs are defined.

Account-create-new-accounts

Click on the application name to display detailed information about the application, and make changes.

The API Credentials for this application is also displayed on this page:

Application-user-key

Note the associated application plan:

Application-plan

Use below values to create four accounts:

Account 1:

Username:                   desktop-user
Email:                      desktop-user@test.com
Password:                   password
Organization/Group Name:    desktop-group

Account 2:

Username:                   mobile-user
Email:                      mobile-user@test.com
Password:                   password
Organization/Group Name:    mobile-group

Account 3:

Username:                   partner-user
Email:                      partner-user@test.com
Password:                   password
Organization/Group Name:    partner-group

Account 4:

Username:                   public-user
Email:                      public-user@test.com
Password:                   password
Organization/Group Name:    public-group

3.7.1. Create Applications using the new APIs

This step is required to create an associated user_key for each API. Click on the top menu item, titled Developers and choose one of the group defined earlier.

Application_create

Click on Application, then click the Create Application link:

Application_create

Select the right corresponding application plan and type an application name:

Application_create

Repeat this step to create the follow applications:

Application_create

3.8. Finish integration

Finally, click on the top API menu item and from there, go to the Integration section of each defined API. Click to edit APIcast configuration and add two more values.

First, add Shared_secret_sent_from_proxy_to_API_backend_12345678987654321 to Secret Token under AUTHENTICATION SETTINGS. For further explanation of this setting, refer to the next chapter.

secret_token

Then, add /products?featured=1 to the input field for API test Get request at the bottom of the page. Notice that the curl command will already include the proper user_key at the end of the URL. This is the new application’s user_key.

API-integration

Press the button to Update & test in staging Environment. If everything is set up properly, the test will go through. The automatically generated curl command can also be used in a shell environment to verify.

[czhu@apimgmt-master ~]$ curl "https://fuse-gateway-service-3scale-apicast-staging.apimgmt.example.com:443/products?featured=1&user_key=032acee45c566dc8b510b0ab7d30be4d"

[{"sku":"5945c1b535c6850001d41aa0","name":"ABC HD32CS5002 32-inch LED TV","description":"HD LED Picture Quality
ConnectShare Movie Wide Color Enhancement Clear Motion Rate 60","length":29.1,"width":3.7,"height":17.5,"weight":17.0,"isFeatured":true,"availability":52,"price":249.99,"image":"TV","keywords":["Electronics","TV"]},........]

3.9. Developer Portal setup

The final step is to set up the Developer Portal. The goal is to let users sign up in the developer portal and immediately get access to the APIs, so they can get started using the API interactive documentation (ActiveDocs, based on Swagger spec), with their own application key.

Click on the top menu item, titled Developer Portal, then select Documentation from the left side panel:

DeveloperPortal

Replace the page source with the Documentation content found in the project repository, and save your changes.

Next, click on Homepage in the left side panel.

DeveloperPortal

Replace the page source with the Homepage content found in the project repository, and save your changes.

3.10. Deploy the presentation application

Deploy the Presentation service, which exposes a web tier for the desktop-user to access the application.

Create a new project for this service:

$ oc new-project desktop-project --display-name="Desktop project for Fuse ecom-services" --description="Desktop project for Fuse ecom-services"

Next, use OpenShift Source-To-Image (S2I) in this project to deploy the presentation service. The presentation_template.yaml file can be found in the project repository. Note that the SERVICE_ADDRESS is passed in as environment variables, while user_key is referenced as an OpenShift Secret in the template; the value for user_key is passed to the template as a parameter.

$ oc new-app -p USER_KEY_VALUE=9331104b50c0385cc64ebd72a38d4a56 -e SERVICE_ADDRESS=fuse-gateway-internal-3scale-apicast-staging.middleware.ocp.cloud.lab.eng.bos.redhat.com -f https://raw.githubusercontent.com/RHsyseng/3scale-apm/master/template/presentation_template.yaml

Chapter 4. Design and Development

4.1. Using Developer Portal

To navigate to the Developer Portal, click on the top menu item titled Developer Portal and then select the Visit Developer Portal link on the next row. This will open the Developer Portal page in a new tab.

DeveloperPortal-usage

By default, the Developer Portal is not visible to the public. Users other than admin will be challenged for the Developer Portal Access Code.

DeveloperPortal-usage

This Access Code can be found in the 3scale API Management Platform Admin Portal. Click on the top menu item, titled Settings, and then choose Developer Portal.

DeveloperPortal-usage

Clearing the value for the Developer Portal Access Code makes the site public, and the address can then be bookmarked for quick access without going through the 3scale API Management Platform Admin Portal.

The Developer Portal allows registered users (desktop-user, mobile-user, partner-user and public-user) to access their own corresponding ActiveDocs. Anonymous users will see the following page, asking them to register and get an API key:

DeveloperPortal-usage

A further attempt by an anonymous user to access the documentation will result in the below page, prompting the user to sign in to see ActiveDocs, but also informing the user of the credentials for the public user account.

DeveloperPortal-usage

Registered users who have logged in will see a page displaying their API key (user_key):

DeveloperPortal-usage

Clicking the DOCUMENTATION link takes an authenticated user to a page that displays the ActiveDocs corresponding to their application plan. For desktop-user and mobile-user, as internal users, this means access to the Fuse-gateway-internal ActiveDoc defined in last chapter, which has access to all services exposed by Fuse gateway service:

DeveloperPortal-usage

For partner-user, access is limited to Fuse-gateway-partner ActiveDocs, which only exposes the product service.

DeveloperPortal-usage

For public-user, only access to Fuse-gateway-public ActiveDoc is provided, limiting such users to only product queries.

DeveloperPortal-usage

The ActiveDocs displayed on the DOCUMENTATION page accelerate development by allowing users to explore services, their parameters and responses.

DeveloperPortal-usage

4.2. Accessing the web application

The presentation application is accessible by the desktop-user and calls Fuse gateway service services. The desktop-user is associated with the internal plan, and this application also makes use of all services.

4.2.1. Browser Access

To run the web application, simply point your browser to the address exposed by the route. This address should ultimately resolve to the IP address of an OpenShift host where the router is deployed.

Figure 4.1. Application Homepage before initialization

Uninitialized Application Homepage

Demo data is populated by hitting the demo.jsp page, for example at http://msa.example.com/demo.jsp. After initialization, this page will show the featured products:

Figure 4.2. Application Homepage after initialization

Application Homepage with Sample Data

4.2.2. User Registration

Anonymous users are constrained to browsing inventory, viewing featured products and searching the catalog. To use other features that result in calls to the Sales and Billing services, a valid customer must be logged in.

To register a customer and log in, click on the Register button in the top-right corner of the screen and fill out the registration form:

Figure 4.3. Customer Registration Form

Customer Registration Form

After registration, the purchase button allows customers to add items to their shopping cart, to subsequently visit the shopping cart and check out, and review their order history.

4.3. Rate Limits

Rate Limit is set up for the public plan. The imposed constraint is a maximum of five requests in every one minute.

To see the effect of this Rate Limit, use the curl command example from the Fuse-gateway-public API integration page.

Click on APIs, choose Fuse-gateway-public, click on Integration link, then click edit APICast configuration link.

The curl command is at the bottom.

API-rateLimit

Execute this command multiple times in succession to exceed the limit and a message of Authentication failed will appear instead of the response data.

API-rateLimit

4.4. Analytics feature

Click on the top menu item titled Analytics to view the Monitoring page, containing usage data for all three APIs.

Analytics

Click on an API name to view more details about it. For example, clicking on Fuse-gateway-public should reveal a spike that results from the multiple curl command invocations intended to the rate limit in the previous section.

Analytics

The usage graph for Fuse-gateway-internal will show multiple calls for different services. These service calls were triggered by the web application on different Fuse gateway service operations.

Analytics

Note that registered users can view associated and accessible Analytics data from the Developer Portal. For example, after signing in to the Developer Portal as the desktop-user, click on STATISTICS to view a graph similar to the one displayed below:

Analytics

4.5. Access control using user_key

This reference architecture uses API Key (user_key) for authentication.

Each application has its own user_key. The keys can be found in respective application pages.

Application-user-key

Each calling application uses the assigned user_key, which corresponds to an API’s application plan. The screenshot below shows an example of an HTTP GET call:

API-integration

The user_key and base URL should not be hard-coded in the application source code, as they are prone to later changes. One good example is the use of OpenShift Secret to managing the user_key in OpenShift , which is referenced in the deployment of the presentation service, for example:

The user_key value is stored in an OpenShift Secret, which is defined in the presentation_template.yaml file:

- apiVersion: v1
  kind: Secret
  metadata:
    name: 3scale-secret
    namespace: desktop-project
  stringData:
    user_key: ${USER_KEY_VALUE}

Further down in the presentation_template.yaml file, content from the Secret is referenced and made available as an environment variable.

      spec:
        containers:
        - env:
          - name: USER_KEY
            valueFrom:
                secretKeyRef:
                    name: 3scale-secret
                    key: user_key

The actual value for user_key is passed in as a parameter during deployment. The use of a parameter instead of an environment variable has the advantage that parameters won’t be kept in memory, so credentials won’t be exposed. Since the base URL is not sensitive information, it can be passed in as an environment variable during pod creation.

$ oc new-app -p USER_KEY_VALUE=9331104b50c0385cc64ebd72a38d4a56 -e SERVICE_ADDRESS=fuse-gateway-internal-3scale-apicast-staging.middleware.ocp.cloud.lab.eng.bos.redhat.com --file=presentation_template.yaml

Then RestClient.java code in the service can then retrieve both data as environment variable values and use them in the web address:

public class RestClient {
    public static String  userKey = System.getenv("USER_KEY");
    public static String serviceAddress = System.getenv("SERVICE_ADDRESS");

For troubleshooting purpose, this reference architecture’s presentation layer uses the JavaScript console to log the two variables' runtime value. This allows users to verify the actual values. To see these two values in Google Chrome, go to setting, More tools, Developer Tools, and click Console.

user_key1

4.6. Prevent bypassing API gateway through secret token

The network topology is often effective in blocking unauthorized access to internal services. When Red Hat 3scale API Management Platform is used to introduce a gateway, direct access to the underlying API is often blocked through network tools. In cases where such configuration is impossible or insufficient, the secret token feature of 3scale API Management Platform can be used to achieve similar results.

When enabled, 3scale API Management Platform hard codes a token in the HTTP header of all requests passing through the gateway. Applications exposing the managed API would then have to check for the existence of this token and reject any requests that do not contain it. As long as the value of this token is kept private, the only way to access such API would be through the gateway.

There are two steps to turn this feature on.

First, in 3scale API Management Platform Admin Portal, click on the top menu item titled API, then choose Integration for the API that needs to be secured. Click the AUTHENTICATION SETTINGS drop-down list and give Secret Token a value.

secret_token

Second, in the application code for the managed API, check all request for a token name of X-3scale-proxy-secret-token in the HTTP header. Reject any requests that do not provide a value for this token, or have an incorrect value.

For example, the following code snippet from the Fuse gateway service shows an example of how to enforce the Secret Token.

    @Value('${gateway.token.header:X-3scale-proxy-secret-token}')
    String tokenHeader

    @Value('${gateway.token.value:#{null}}')
    String tokenValue

    Logger logger = Logger.getLogger(AppRoute.class.name)

    @Override
    void configure() throws Exception {

        if (tokenValue != null && tokenHeader != null) {

            logger.info("AUTH TOKEN REQUIREMENT DETECTED: [${tokenHeader}] adding security route interceptor")
            interceptFrom().id("auth token interceptor").process(new Processor() {
                @Override
                void process(Exchange exchange) throws Exception {

                    if (exchange.in.getHeader(tokenHeader) == null
                            || exchange.in.getHeader(tokenHeader) != tokenValue) {

                        logger.info("Authorization token required, but header missing or invalid")
                        exchange.out.setHeader(Exchange.HTTP_RESPONSE_CODE, 403)
                        exchange.out.setBody("Unauthorized [missing or invalid token]")
                        exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE)
                    }
                }
            })
        }

The secret token in inject into the Fuse gateway service pod as an environment variable to avoid hard-coding it.

secret_token

In this example, the token value is set to Shared_secret_sent_from_proxy_to_API_backend_12345678987654321. Changing this value in the 3scale API Management Platform Admin Portal without updating it in the Fuse gateway service code would result in the API integration test failing, since the value passed from 3scale API Management Platform to Fuse gateway service will not match.

secret_token

Once the security token is set up, both in 3scale API Management Platform and Fuse gateway service, requests to the Fuse gateway service API need to go through 3scale API Management Platform first; otherwise, the request will fail, as it will not have the secret security token in the header.

To demonstrate this, try the two following curl commands to the same Fuse gateway service API, where the first one bypasses the 3scale API Management Platform and uses the Fuse gateway service gateway IP address directly, while the second request goes through 3scale API Management Platform as expected.

curl http://172.30.124.155:9091/products?featured=1

curl "https://fuse-gateway-internal-3scale-apicast-staging.middleware.ocp.cloud.lab.eng.bos.redhat.com:443/products?featured=1&user_key=876286f7c3cf24899c6f390464c41429"

The first requests fails with a message of missing or invalid token, while the second command returns the expected response.

secret_token

4.7. Updating Swagger files

To create a new service spec, the swagger file for the new service is required. The reference architecture’s Fuse gateway service provided a swagger file at http://api.example.com/api-doc/swagger.json after installation. Several updates are required to this file before it can be used in this project:

  • Update the host to the correct value. Red Hat 3scale API Management Platform doesn’t allow IP address, so please use either the Staging Public Base URL or the Production Public Base URL instead:
"host" : "fuse-gateway-service-3scale-apicast-staging.apimgmt.example.com:443",
  • Update the scheme to HTTPS, as it is the default protocol used by 3scale API Management Platform:
"schemes" : [ "https" ],
  • For each service, add one more parameter called user_key for authentication. This parameter is not included in the Swagger file originally provided by the Fuse gateway service.

Note that only one parameter called customerId is included in the file:

    "/customers/{customerId}" : {
      "get" : {
        "tags" : [ "customers/{customerId}" ],
        "summary" : "get customer",
        "produces" : [ "application/json" ],
        "parameters" : [ {
          "name" : "customerId",
          "in" : "path",
          "description" : "id of customer to fetch",
          "required" : true,
          "type" : "string"
        } ],
        "responses" : {
          "200" : {
            "description" : "customer fetched",
            "schema" : {
              "$ref" : "#/definitions/Customer"
            }
          }
        },
        "x-camelContextId" : "camel-1",
        "x-routeId" : "route7"
      },

Add the new parameter:

    "/customers/{customerId}" : {
      "get" : {
        "tags" : [ "customers/{customerId}" ],
        "summary" : "get customer",
        "produces" : [ "application/json" ],
        "parameters" : [ {
          "name" : "customerId",
          "in" : "path",
          "description" : "id of customer to fetch",
          "required" : true,
          "type" : "string"
        },
        {
            "name": "user_key",
            "in": "query",
            "description": "Your API access key",
            "required": true,
            "x-data-threescale-name": "user_keys",
            "type": "string"
        }
         ],
        "responses" : {
          "200" : {
            "description" : "customer fetched",
            "schema" : {
              "$ref" : "#/definitions/Customer"
            }
          }
        },
        "x-camelContextId" : "camel-1",
        "x-routeId" : "route7"
      },

4.8. Developer Portal DOCUMENTATION page

Liquid is a simple programming language used for displaying and processing most of the data from the 3scale system available for API providers.

Use Liquid control flow tags if and elsif to limit access for each registered user to their own ActiveDocs:

      	{% if current_user.username == 'desktop-user' or  current_user.username == 'mobile-user' %}
          {% active_docs version: "2.0" services: "Fuse-gateway-internal" %}
            ...............

      	{% elsif current_user.username == 'partner-user' %}
          {% active_docs version: "2.0" services: "Fuse-gateway-partner" %}
            ...............

      	{% elsif current_user.username == 'public-user' %}
          {% active_docs version: "2.0" services: "Fuse-gateway-public" %}
            ...............

		{% endif %}

Refer to the product documentation on how to publish ActiveDocs in the Developer Portal.

          <script type="text/javascript">
            $(function () {
                window.swaggerUi.options['docExpansion'] = 'none';
                window.swaggerUi.options['url'] = "https://3scale.apimgmt.example.com/swagger/spec/Fuse-gateway-internal.json";
              window.swaggerUi.load();
            });
          </script>

For more information on using Liquid and Developer Portal, please refer to Liquids: Developer Portal and the Liquid Reference pages.

Appendix A. Revision History

RevisionRelease DateAuthor(s)

1.0

August 2017

Calvin Zhu

Appendix B. Contributors

We would like to thank the following individuals for their time and patience as we collaborated on this process. This document would not have been possible without their many contributions.

ContributorTitleContribution

Babak Mozaffari

Manager, Software Engineering
& Consulting Engineer

Technical Content Review

Jeremy Ary

Senior Software Engineer

Technical Content

Andrew Mackenzie

Director, Software Engineering

Technical Content Review

Vanessa Ramos

Senior Product Manager

Technical Content Review

Hugo Guerrero

Senior Principal Product Marketing Manager

Technical Content Review

Appendix C. Revision History

Revision History
Revision 1.0-0August 2017CZ

Legal Notice

Copyright © 2017 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat Software Collections is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.