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

IBM/security-verify-reactjs-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

51 Commits
 
 
 
 
 
 
 
 

Repository files navigation

abstract authors completed_date components draft excerpt keywords last_updated primary_tag pta pwg related_content related_links runtimes series services subtitle tags title translators type
Add SSO to a ReactJS based application using IBM Security Verify
name email
Shikha Maheshwari
name email
Balaji Kadambi
true|false
Add SSO to a ReactJS based application using IBM Security Verify
security verify, security, sso
security
cloud, container, and infrastructure
security
type slug
announcements|articles|blogs|patterns|series|tutorials|videos
liberty for java
type slug
security-verify
Provide a single point access to enterprise applications and monitor their usage
Add SSO to a ReactJS based application using IBM Security Verify
name email
tutorial|howto

React is a JavaScript library for building user interfaces and is used to build single-page applications. SSO(Single Sign-on) is an authentication scheme that allows the user to log in once and access services without re-entering passwords. IBM Security Verify provides identity-as-a-service for every user, including Single sign-on(SSO), risk-based Multi factor authentication(MFA) and adaptive access, user lifecycle management, and identity analytics. In this tutorial, you will learn how to add SSO feature in your React application using the IBM Security Verify.

Security Verify includes SAML and OIDC cloud based federated single sign-on with connectors. OpenID Connect v1.0 (OIDC) is a modern standard for web single sign-on. It adds an identity layer to the OAuth 2.0 standard. These standards are popular because they have simple client-side implementations, making it easy for you to get connected. The standards support different grant types for different use cases. For web applications, the Authorization code grant type is the most commonly used and most widely supported. We will use the Authorization code grant type for this tutorial.

The tutorial covers the below aspects:

  • Create a sample microservices based application using React for front-end service

    The sample application contains three microservices:

    (a) Front-end UI service built using React that interacts with back-end services

    (b) Weather service built on Node.js that returns the weather information for a provided location

    (c) User information service built on Open Liberty with Java that returns user details stored in Security Verify

    The application code is provided here.

  • Enable and configure verify-sdk for the React application to enable authentication
    In this tutorial, we demonstrate a strategy to use verify-sdk with the React app. The Verify-SDK is a JavaScript SDK. It is used to integrate with IBM Security Verify as it provides the method to obtain identity token, access token and some more. This configuration re-directs the request to Security Verify for authentication and comes back to React app with a valid token after successful authentication.

  • Adding and configure the application on IBM Security Verify for SSO
    The application can be deployed anywhere - On-premise or on any Cloud provider. We will deploy the application on OpenShift(on IBM Cloud) for this tutorial to demonstrate the procedure. The configuration steps would remain the same irrespective of the cloud provider. The application will be registered with Security Verify.

  • Protect other paths on the application using token introspection with Security Verify
    The sample application has two other microservices as part of the solution - weather service and user info service. The weather service is a Node.js microservice and user info service is a Java microservice. The APIs exposed by both these services are protected. Once an user is authenticated with Security Verify, an access token is retrieved. This access token is sent back to the browser and stored as a secure cookie. This cookie is sent to the server for all other subsequent API calls. In the API implementations, the token is introspected with Security Verify for validity. If the token is valid, the API access is allowed else the access is rejected.

  • Monitor the usage of the application on Security Verify
    The Security Verify Dashboard can be used to generate reports on the application usage with details of number of user logins. The logins can be further analyzed to check for successful and unsuccessul login attempts.

Prerequisites

Estimated time

Completing this tutorial should take about 45 minutes.

Steps

1. Add a custom application on Security Verify

Login to Security Verify. Select Applications from the menu.

selectapp

Click on Add application to add an application.

clickapp

Select the application type as Custom Application. Click on Add application.

addapp

Enter a name(say ReactApp) for the application and a Company name.

enterdetails

You will now configure SSO using the OpenID Connect based authentication with Authorization code scheme. Click on the Sign-on tab. Configure as follows:

  • Select the Sign-on method as Open ID Connect 1.0.
  • Enter the Application URL say http://localhost:3002.

Note: The Application URL will be replaced with the OpenShift deployment URL for the front-end service. This localhost configuration will work if the front-end application is deployed locally.

  • Choose Grant types as Authorization code.
  • Unselect the option Require proof key for code exchange (PKCE) verification.
  • Enter Redirect URIs say http://localhost:3002/redirect.

Note: The Redirect URIs will be replaced with the OpenShift deployment URL for the front-end service. This configuration will work if the front-end application is deployed locally.

  • Click on Save to save the configuration.

configuresso

Select Access Type as Automatic access for all users and groups. Click on Save.

selectaccess

Go to Applications menu and select the row with the newly created Liberty App. Click the Settings icon.

opensavedapp

Goto the Sign-on tab. Note down the below:

  • Client ID
  • Client secret.

notecreds

Next, note down the IBM Security Verify endpoint.

openendpoint

Open the IBM Security Verify endpoint in a new browser tab. Note down the below endpoints:

  • introspection_endpoint

Also, note down the registration profile id. On the Security Verify dashboard, go to Authentication and then Registration Profiles. Note the Profile ID for the Security Verify profile.

Make a note of the Base URL for your Security Verify instance - https://[tenant id].verify.ibm.com.

The Security Verify Base URL, client ID, client secret, Profile ID and Introspection endpoint URL will be used in subsequent sections.

2. Add a new user to Security Verify

The users will be required for testing purpose. Users can be added using APIs through an application or using Security Verify dashboard. This tutorial adds users through dashboard.

Go to Users & Groups to add a new user. Click on Add user.

adduser

Select Identity source as Cloud Directory. Enter values for Given name and Surname. Enter any valid e-mail address for Work e-mail. Click on Save.

configureuser

Check your e-mail for a confirmation mail from Security Verify. The email contains a temporary password and a link to login to Security Verify. Login to Security Verify and change your password.

confirmemail

Repeat the same steps to add more users.

3. Setup the environment to deploy the services

Create an OpenShift cluster

Login to your IBM Cloud account and create an OpenShift cluster if not created before.

Clone the GitHub repository

Open a terminal and clone the GitHub repository by running the following command:

git clone https://github.com/IBM/security-verify-reactjs-tutorial

Login to your OpenShift cluster from command line

Login to your OpenShift cluster. Access the IBM Cloud Dashboard > Clusters (under Resource Summary) > click on your OpenShift Cluster > OpenShift web Console. Click the dropdown next to your username at the top of the OpenShift web console and select Copy Login Command. Select Display Token and copy the oc login command from the web console and paste it into the terminal on your workstation. Run the command to login to the cluster using oc command line.

4. Deploy the weather service

This service uses the WeatherAPI provided by OpenWeather.

Get API key from Open Weather Map

Sign up on https://openweathermap.org/api. Subscribe to the Current Weather Data and note the API Key.

Configure the API key for Open Weather API

Open the file weather.service.ts under sources/weather-svc/src/services in the repo you cloned earlier. Replace <<apikey>> in the line (shown below) with the API key for the Open Weather API you noted, and save the file.

const url = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=<<apikey>>';

Configure Security Verify endpoints for token introspection

Open the file weather-controller.ts under sources/weather-svc/sources/weather-svc/src/controllers/ directory in the cloned repo folder.

At around line 35(see code snippet below), there are placeholders for introspection_endpoint({{security verify introspection url}}), Client ID({{client id for security verify}}) and Client Secret({{client secret for security verify}}). Replace the placeholder strings with the introspection_endpoint, Client ID and Client Secret that you noted for Security Verify configuration, and save the file.

let data1 = qs.stringify({
      client_id: '{{client id for security verify}}',
      client_secret: '{{client secret for security verify}}',
      token: tokenvalue
    });

    const response = await fetch('{{security verify introspection url}}', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: data1
    });

On a terminal, go to the sources/weather-svc directory in the clone repo folder. Run the below commands:

oc new-project weather
oc new-app . --name=weather-svc --strategy=docker
oc start-build weather-svc --from-dir=.
oc logs -f bc/weather-svc
oc expose svc/weather-svc

Ensure that the service is started successfully using the command oc get pods. Also make a note of the route using the command oc get routes. The route will be required in the configuration of the front-end microservice.

5. Deploy the user info service

Open the file verify.config under user-info-svc/src/main/resources. Add the introspection_endpoint, Client ID and Client Secret that you noted for Security Verify configuration as shown below, and save the file:

introspectionUrl=https://[[tenant id]].verify.ibm.com/v1.0/endpoint/default/introspect
clientId=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
clientSecret=xxxxxxxxxx

On a terminal, go to the sources/user-info-svc directory in the clone repo folder. Run the below commands:

oc new-project userinfo
oc new-app . --name=user-info-svc --strategy=docker
oc start-build user-info-svc --from-dir=.
oc logs -f bc/user-info-svc
oc expose svc/user-info-svc

Ensure that the service is started successfully using the command oc get pods. Also make a note of the route using the command oc get routes. The route will be required in the configuration of the front-end microservice.

6. Build & Deploy frontend service

The front-end service generally communicates with back-end services using a Gateway service in a development environment. In a production set-up, frontend service and gateway service are deployed as single application. Read this blog to get more understanding on how-to achieve this in a React application. The sample application provided here demonstrates the same.

The React code of frontend service is available at sources/frontend-gateway-svc/ui-react and the code to integrate with verify-sdk and other services is available at sources/frontend-gateway-svc/server.js.

Build frontend(React) code

As a next step, go to the cloned code and navigate to sources/frontend-gateway-svc/.

To build react code, perform the following steps:

cd ui-react
npm install
npm run build
rm -rf node_modules

The front-end(UI) code is built and creates ui-react/build folder.

Configure Verify-SDK and other service URLs

Navigate to sources/frontend-gateway-svc/ and copy the .env.sample as .env.

Open the file .env. Replace the placeholders with the Security Verify Base URL, Client ID, Client Secret, Profile ID, route of weather service, route of user-info service that you noted earlier, and save the file.

TENANT_URL=https://{{tenant id}}.verify.ibm.com
CLIENT_ID={{Client ID}}
CLIENT_SECRET={{Client Secret}}
RESPONSE_TYPE=code
FLOW_TYPE=authorization
SCOPE=openid
REGISTRATION_PROFILE_ID={{Profile ID}}

WEATHER_SERVICE_URL=
USER_PROFILE_SERVICE_URL=

Deploy frontend service

On a terminal, go to the sources/frontend-gateway-svc directory in the cloned repo folder. Run the below commands:

oc new-project frontend
oc new-app . --name=ui-svc --strategy=docker
oc start-build ui-svc --from-dir=.
oc logs -f bc/ui-svc
oc expose svc/ui-svc

Ensure that the service is started successfully using the command oc get pods. Get the route using the command oc get routes. The application will be accessible using this route.

Update the application URL and redirect URI in Security Verify

Access the Security Verify and update application URL and redirect URI with the frontend service route as explained in Step 1.

Application URL - http://xxx-0000.us-south.containers.appdomain.cloud
Redirect URI - http://xxx-0000.us-south.containers.appdomain.cloud/redirect

7. Access the application

Access the frontend service route using a browser. You can perform the following functionality in the application.

  • Login through Security Verify using the user(s) added in step 2.
  • After login, either you can check user profile or get weather updates.
  • Clicking on Get My Profile, will fetch the information from the user profile created in Security Verify.
  • Clicking on Get Weather Updates, will give the weather information for the provided location.
  • If you try to access the APIs directly without login, it will throw an error as Unauthorised access because all services perform token introspection anf fails for invalid token.

demo

8. Monitor application usage

You can generate a report for an application. Navigate to Reports. Select the application and click on View Report.

viewreport

View user activity for the application:

appreport

Summary

In this tutorial, you added SSO to a React.JS based application with Security Verify. You have learnt how back-end microservices can be protected with Security Verify. Hope you found the tutorial useful!

If you wish to use Spring Security to integrate your Java application with Security Verify please refer to the tutorial - Protect enterprise applications with single sign-on (SSO) and monitor their usage using IBM Security Verify.

If you wish to integrate an application on Open Liberty with Security Verify, please refer to the tutorial - Configure Open Liberty to integrate with IBM Security Verify for SSO.

You can explore further to see how SSO can be added to Node, Android or iOS applications. In addition, the tutorial Modern authentication protocols provides a good introduction to Security Verify and implementing SSO for a Node.js application.

About

Source code for the Security Verify Reactjs tutorial

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •