Skip to content

Latest commit

 

History

History

lab06

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Lab 6

API Consumption

Connect Applications and APIs

  • Duration: 15 mins
  • Audience: API Consumers, Developers, Architects

Overview

APIs provide the building blocks for applications, but it is applications which deliver functionality to the end users. hence to see APIs in action it helps to see how applications can call APIs to provide new functionality. In this lab you'll be able to create a simple web application which consumes the API you built earlier ojn in the exercises.

Why Red Hat?

Applications can be built from many technologies. In this case we use a simple web application, but a wide range of Red Hat and non-Red Hat technologies could be used.

Skipping The Lab

If you decide to skip the lab you can check how a SSO enabled web applications looks like:

http://www-international.apps.GUID.openshiftworkshop.com

Environment

URLs:

Check with your instruction the GUID number of your current workshop environment. Replace the actual number on all the URLs where you find GUID.

Example in case of GUID = 1234:

https://master.GUID.openshiftworkshop.com

becomes =>

https://master.1234.openshiftworkshop.com

Credentials:

Your username is your asigned user number. For example, if you are assigned user number 1, your username is:

user1

The password to login is always the same:

openshift

Lab Instructions

Step 0: Setup the collaboration environment using Git (Gogs)

For this lab we require a collaboration environment based on Git. You can use GitHub, GitLab or other Git provider to finish this lab. If you don't want to use your personal account, the provided lab environment has an user provided for you in Gogs.

Follow this instructions to set up the repository.

  1. Open a browser window and navigate to:

    http://gogs.apps.GUID.openshiftworkshop.com/user/login?redirect_to=
  2. Log into Gogs using your designated user and password. Click on Sign In.

    gogs-sign-in

  3. In the main page, click in the + sign in the right top corner to display the New menu. Click the New Migration option.

    gogs-new

  4. Fill in the information of the repository migration with the following values:

    gogs-migration

  5. Click on Migrate Repository to fork the GitHub repo into Gogs.

    You now have a working copy of the International Inc Web page. If you know how to, clone the repository to work locally, or you can continue working using Gogs online editor.

Step 1: Deploying International Inc Web Page

International Inc web development create a Node.js application for the company home page. They added a map service to locate the offices around the world. In this step you will deploy that application.

  1. Open a browser window and navigate to:

    https://master.GUID.openshiftworkshop.com/console

    Remember to replace the GUID with your environment value and your user number.

  2. Accept the self-signed certificate if you haven't.

    selfsigned-cert

  3. Log into OpenShift using your designated user and password. Click on Sign In.

    01-login

  4. You are now in OpenShift's main page. Click on your userX project in the right side of the screen.

    02-user-project

  5. From your main project page, click Browse Catalog.

    03-browse-catalog

  6. Scroll down the page and search for the Node.js template. Click on the link.

    04-nodejs-template

  7. Click the Next > button.

    05-template-information

  8. Fill in the configuration information with your API implementation github repo details:

    Remember to replace the GUID with your environment value and your user number.

    06-template-configuration

  9. Click Create.

  10. Your service will be provisioned in a moment. Click the Continue to the project overview link.

    08-template-results

    If you clicked the Close button, click Overview in the left side menu to review the deployment status.

  11. From your overview page, click the white space next to the www link to expand the deployment information.

    09-deployment-config

  12. Scroll down and click in the www link in the BUILDS section.

    10-builds

  13. In the build configuration page, change to the Environment tab. Fill in the available row with the following information:

    Remember to replace the GUID with your environment value and your user number.

    11-environment

    Click the Add Value link to enable a new row if not already present.

  14. Click Save button to persist the changes. A green pop up will show you that the changes were saved.

  15. Click the Start Build button to trigger a new build using the new environment variables pointing to your service.

    12-start-build

  16. Click the Overview menu option on the left side to go back to the your project overview page.

  17. In the overview page, wait until the running Build is complete and the pod circle stays blue continously. This means the application was successfully deployed and now is ready to listen to requests.

    13-build-complete

  18. Click the Routes - External Traffic to open a new tab and connect to International Inc new website.

  19. You should now see what the development team created for International Inc. Click LOCATIONS to check the locations page.

    10-application-page

  20. This pages uses the unsecured Location API service. It displays the different International Inc offices around the world.

    11-locations-page

  21. In the next step we will update the Locations page to use the 3scale protected API.

Step 2: Calling a Secured Service with Red Hat Single Sign On

In this step, we will edit the code provided by development to add keycloak. Keycloak is the upstream project powering Red Hat Single Sign On. The Keycloack Javascript Adapter simplifies the required code to interact with the OpenID Connect authentication flows.

  1. Go back to your Git repository and navigate to dev folder.

    15-dev-folder

  2. Click on the locations.html link to open the file.

    16-locations-file

  3. Change to edit mode clicking on the pencil icon on the right side.

    17-locations-edit

  4. Scroll down the page an look for the following code:

    <!-- Keycloak Adapter Start-->
    
    <!-- Keycloak Adapter End -->
  5. Import the Javascript Adapter library by pasting between the previous markers the following code:

    <script src="SSO_URL/auth/js/keycloak.js"></script>
  6. Continue scrolling down until you find the next markers:

    <!-- Keycloak Login Start -->
    
    <!-- Keycloak Login End -->
  7. Here we will add a Login button so users can start the Authentication Flow. It will disapear and be replaced with the map when user is logged in. Paste between the markers the following code:

    <p><a id="loginUrl" href="#" class="btn btn-primary">Sign In to access the Location API Service</a></p>
  8. Continue scrolling down until you find the next markers:

    // Keycloak Config Start
    
    callService(mymap)
    
    // Keycloak Config End
  9. Replace the code between the markers with the following snippet:

    var keyOptions = {
        url: 'SSO_URL/auth',
        realm: 'SSO_REALM',
        clientId: 'CLIENT_ID'
    };
    
    var keycloak = Keycloak(keyOptions);
    keycloak.init({ onLoad: 'check-sso' }).success(function (authenticated) {
        if (authenticated) {
            $("<h4>Welcome " + keycloak.idTokenParsed.preferred_username + "</h4> ").insertBefore($('#mapid'));
            callService(mymap, keycloak.token);
            $('#mapid').show();
            $('#loginUrl').hide();
        }
        else {
            $('#mapid').hide();
            $('#loginUrl').show();
        }
    }).error(function (data) {
        alert('Failed to initialize keycloak: ' + data);
    });
    
    var opts = {
        redirectUri: window.location.origin + "/locations.html"
    };
    
    var loginUrl = keycloak.createLoginUrl(opts);
    document.getElementById('loginUrl').href = loginUrl;
  10. Continue scrolling down until you find the next markers:

    /* Keycloack Params Start*/
    
    /* Keycloak Params End */
  11. Paste between the markers the following code:

    , token
  12. Finally the last marker:

    // Keycloak Ajax Start
    
    // Keycloak Ajax End
  13. Paste between markers the last snippet:

    // Keycloak Ajax Start
    headers: {
         'Authorization': 'Bearer ' + token
    },
    // Keycloak Ajax End
  14. Scroll to the bottom of the page. Update the Commit Changes inputs and click Commit Changes to save your work.

    18-commit-changes

  15. Because we are using self signed certificates, you will need to accept the certificate for the secured endpoint. Open a new browser tab or window and navigate to:

    https://location-userX-api-staging.amp.apps.GUID.openshiftworkshop.com/locations

    Remember to replace the GUID with your environment value and your user number.

  16. Accept the self-signed certificate if you haven't.

    selfsigned-cert

  17. You will see that your call succeded if you see the following text in your browser:

    Authentication parameters missing

Step 3: Update Red Hat Single Sign On Application Callback

Redirect URLs are a critical part of the OAuth flow. After a user successfully authorizes an application, the authorization server will redirect the user back to the application with either an authorization code or access token in the URL. Because the redirect URL will contain sensitive information, it is critical that the service doesn’t redirect the user to arbitrary locations.

  1. Open a browser window and navigate to:

    http://sso-rh-sso.apps.GUID.openshiftworkshop.com/auth/admin/userX/console/

    Remember to replace the GUID with your environment value and your user number.

  2. Log into Red Hat Single Sign On using your designated user and password. Click on Sign In.

    00-login-sso.png

  3. Select Clients from the left menu.

    00-clients.png

    3scale, through it's zync component, already synchronized the application information into the Red Hat SSO security realm.

  4. Click on the CLIENT_ID link to view the details.

    24-client-application

    Remember to replace CLIENT_ID with the one you got in the API Security Lab. It will easily identificable as its and hexadecimal name.

  5. Scroll down, type in and select the following options in the application configuration:

    Remember to replace the GUID with your environment value and your user number.

    25-client-config

  6. Finally, click Save button to persist the changes.

Step 4: Updating OpenShift Deployment

OpenShift let you automatically redeploy your changes when you setup a Continuous Integration / Continuous Deployment (CI/CD) pipeline through the use of webhook. For this lab we will trigger the new build and deployment manually through the OpenShift Console.

  1. Go back to your OpenShift web console. Navigate to your project's overview page.

  2. Scroll down and click in the www link in the BUILDS section.

    10-builds

  3. In the build configuration page, change to the Environment tab.

  4. Replace the unprotected endpoint URL with the new value of your 3scale-protected Location Service API URL. Also add this new three environment variables SSO_URL, SSO_REALM and CLIENT_ID.

    Click Add Value to add additional rows.

    Replace REPLACE_ME with the Client ID you got in the API Security Lab, it should look like e343da3. Remember to replace the GUID with your environment value and your user number.

    14-environment

  5. Click Save button to persist the changes. A green pop up will show you that the changes were saved.

  6. Click the Start Build button to trigger a new build using the new environment variables pointing to your service.

    12-start-build

  7. A new build will be triggered. Expand the row by clicking the Builds Icon.

    20-build-configuraion

    The build process checks out the code from the git repo, runs a source-to-image container image build, and redeploys the container with the new image using a rolling upgrade strategy.

  8. Wait for until the new Build to complete and the rolling upgrade to finish to test your new deployment.

    21-build-complete

  9. Refresh the browser tab where you opened the International Inc web page or click the route URL to check out the changes.

    22-updated-app

    You can notice now the Sign In button in the page.

Step 5: Test the Single Sign On Integration

  1. Let's test the integration. Click the Sign In button.

  2. You are being redirected to Red Hat Single Sign On Login Page. Login using the user credentials you created in the API Security Lab

    • Username: apiuser
    • Password: apipassword

    23-realm-login

  3. You will be redirected again to the LOCATIONS page where now you will be able to see the map with the International Inc Offices.

    11-locations-page

Congratulations! You have successfully used the Keycloak Javascript Adapter to protect International Inc's Locations Service with Single Sign On.

Steps Beyond

So, you want more? You can explore in detail the documentation on the Javascript Adapter to check what other things can you get from your authenticated user.

Summary

In total you should now have been able to follow all the steps from designing and API, deploying it's code, issuing keys, connecting OpenID connect and calling it from an application. This gives you a brief overview of the creation and deployment of an API. There are many variations and extensions of these general principles to explore!

This is the last lab of this workshop.

Notes and Further Reading