IBM Developer

Article

Secure your chatbot experience with IBM Security Verify

Ensure your watsonx Assistant conversations are personalized and protected

By Sushmita Das, Rahul K P

Today's modern organization is dynamic, and employees can assume diverse roles that determine their responsibilities and information needs. IBM watsonx Assistant empowers businesses to create chatbot experiences tailored to these roles through role-based access control (RBAC), ensuring users receive relevant and personalized interactions. And how do you determine the user's role? You fetch it from IBM Security Verify using REST APIs.

Component technologies

This use case comprises multiple technologies, including watsonx Assistant, IBM Security Verify, and IBM Cloud Code Engine Functions. This combination provides seamless integration; the code is built using Python and deployed as a Code Engine function. Alternatively, you can use Azure Functions or an AWS Lambda serverless computing service.

watsonx Assistant

IBM watsonx Assistant is an AI-powered virtual agent that provides fast, consistent, and accurate answers across any messaging platform, application, device, or channel.

Using large language models (LLMs) and an intuitive user interface, watsonx Assistant enables you to build AI-powered voice agents and chatbots that deliver automated self-service support across channels and provide seamless integration with your business tools.

IBM Cloud Code Engine Functions

IBM Cloud Code Engine Functions are event-driven, serverless solutions for stand-alone code that is deployed on an IBM Cloud network. Functions can be run without provisioning or managing servers, which saves infrastructure costs. They support many programming languages, including Python and Java.

This use case uses Python and deploys code as a Code Engine Function. Alternatively, you can use Azure Functions or an AWS Lambda serverless computing service.

OpenAPI

The OpenAPI Iniative establishes an open standard for describing and documenting REST APIs. An OpenAPI document defines the resources and operations that are supported by an API, including request parameters and response data, along with details such as server URLs and authentication methods.

An OpenAPI document describes a REST API in terms of paths and operations. A path identifies a particular resource that can be accessed by using the API (for example, a hotel reservation or a customer record). An operation defines a particular action that can be performed on that resource (such as creating, retrieving, updating, or deleting it).

OpenAPI specifies all of the details for each operation, including the HTTP method, request parameters, the data included in the request body, and the structure of the response body.

IBM Security Verify SaaS

<a href="https://www.ibm.com/products/verify>IBM Security Verify SaaS is a cloud-based IAM solution that has hybrid cloud deployment options. It provides automated, cloud-based, and on-premises capabilities for administering identity governance, managing workforce and consumer identity and access, and controlling privileged accounts.

Verify SaaS includes:

  • Core identity base capabilities for both your workforce and consumers, including adaptive access and advanced authentication capabilities that are powered by IBM Security Trusteer's AI-enabled engine
  • Single sign-on for centralized access control to cloud and on-premises resources
  • Adaptive access for risk-based authentication
  • Advanced authentication for frictionless access
  • Embedded privacy and consent management capabilities that are prebuilt into easy-to-adopt workflows
  • Full lifecycle management to connect application access with business governance workflows

You can use this workflow for both internal users or consumers. The workflow can act as a first layer of user verification. Different options are shown depending on the user’s profile, role, or department. For example, if the user is accessing the assistant as an employee, they receive different options than a user who is a consumer.

High-level architecture

The following figure shows the high-level architecture of the developed solution. The user (employee) accesses the chatbot through a browser on either their mobile device, laptop, or desktop machine. Before the user can use the authorized services available to them, they must authenticate through Verify using its REST APIs, which are deployed as stand-alone code and can be invoked through watsonx Assistant. Once the authentication is successful, the user can see the set of services available to them and proceed with the interaction.

High=level architecture

Prerequisites

Steps

The following steps provide a high-level walk-through, including screen shots, on how to integrate watsonx Assistant with IBM Security Verify SaaS using Actions. We have included links to product documentation to find more details on specific steps.

Step 1. Import the code

  1. Import the code into Code Engine. This searches the user in the Verify SaaS tenant and retrieves the emailid/pmobile/role, which are needed in furure steps for user authentication and authorization.

       import requests
       import os
       import json
       tenantid=os.getenv('tenantid')
       clientid=os.getenv('clientid')
       clientsecret=os.getenv('clientsecret')
       def main(params):
          access_token=accountlookup(params)
          return {
          "headers": {
                   "Content-Type": "application/json",
             },
          "body":access_token
          }
       def auth():
       tokenurl = tenantid + ":443/oauth2/token"
       tokenpayload = "grant_type=client_credentials&client_id=" + clientid + "&client_secret=" + clientsecret + "&scope=openid"
       headers = {
             'Content-Type': "application/x-www-form-urlencoded"
             }
       response = requests.request("POST", tokenurl, data=tokenpayload, headers=headers)
       return response.json()["access_token"]
       def accountlookup(userName):
          capturedName=userName['name']
          print("Final Username:", capturedName )
          access_token = auth()
          print("Access Token:", access_token)
          url = tenantid + "/v2.0/Users?filter=userName eq \"" + capturedName + "\""
          payload = ""
          headers = {
             'Authorization': "Bearer "+access_token,
             }
          response = requests.request("GET", url, data=payload, headers=headers)
          print("URL: ", url)
          response = requests.request("GET", url, data=payload, headers=headers)
          userrole=', '.join(response.json()["Resources"][0]["urn:ietf:params:scim:schemas:extension:ibm:2.0:User"]["customAttributes"][0]["values"])
          print("JSON: ", response.json())
          if response.status_code == 200:
             if response.json()["totalResults"] != 0:
                   print("Total", response.json())
                   resp={
                         'message': "I found your account.",
                         'user_email': response.json()["Resources"][0]["emails"][0]["value"],
                         'user_id': response.json()["Resources"][0]["id"],
                         'cell_phone': response.json()["Resources"][0]["phoneNumbers"][0]["value"],
                         'role': userrole,
                         'status_code': 200
                   }
             else:
                   resp = {'messages': "I'm sorry, I can't find that account. Can you try again?",
                         'status_code': 400
                   }
          else:
             resp = {'messages': "Oops... that didnt work.",
                      'status_code': 400
             }
          print("Response: ", resp)
          return (resp)
    

    Note: For instructions on how to deploy the code, see Creating function workloads from local source code in the Code Engine documentation.

  2. Use the IBM Cloud Code Engine Function endpoint to generate the OpenAPI document. For details, see the OpenAPI Specification.
  3. Create environment variables for tenantid, clientid, and clientsecret. alt

Step 2. Generate the specification

  1. Generate the OpenAPI spec to search users and send/validate an email or phone one-time password (OTP).
  2. When the spec has been created, create an extension. See Building a custom extension in the watsonx Assistant documentation for details on how to create extensions. User Search
  3. In the Authentication tab, specify the IBM Cloud Code Engine Function endpoint for the UserSearch extension. OTP Send & Validate

Step 3. Create Actions

  1. When you have created the extensions, create the Actions to specify the workflow. alt
  2. Attach the extension to search user. alt
  3. To edit the extension, select the appropriate values from the fields' drop-down menus. alt

Note: For more details on importing or exporting actions in your local environment, see the set of steps following Step 4, below.

Step 4. Store the response

  1. Store the API responses in the variables. You need to collect the values to use them later in the conversation. (See Create a new variable below to create a new variable from an action step in watsonx Assistant.) watsonx Assistant screen
  2. Create a step to send and validate the OTPs and take the conversation forward based on the response. See Calling a custom extension in the watsonx Assistant documentation for details on how implement extensions with Actions.

Import and export actions

  1. Log in to your watsonx Assistant instance and in the menu, click Actions.
  2. Click the Global settings button. watsonx Assistant global settings
  3. Click the Upload/Download button.
  4. Click Upload and select the actions sets you previously downloaded. Alternatively, click Download to get existing actions sets. watsonx Assistant screen

Note: Ensure that you have integrated the custom extensions that are part of the actions you are uploading. They are essential for the uploaded actions to function properly. See the watsonx Assistant documentation on Building a custom extension and Adding an extension to your assistant for details.

Create a new variable

To create a new variable used in Step 4. Store the response, above, complete the following steps:

  1. Log in to watsonx Assistant, click Actions, and select the specific action. watsonx Assistant menu
  2. Select the specific step.
  3. Click Set variable values and then select New session variable. Set variable values screen watsonx Assistant interface
  4. Provide the variable details in the dialog field.
  5. Click Apply. Session variable screen capture

For more details, see Choosing a response type in the watsonx Assistant documentation.

Summary

In this tutorial, you've seen how an interactive chatbot enables users to actively engage in conversation protected by a security layer. The use case takes advantage of the integration capabilities of IBM watsonx Assistant, IBM Cloud Code Engine, and IBM Security Verify SaaS to build a robust, flexible and secure solution. With user authentication embedded in the initial stages of the conversation, users get more tailored responses to their queries.

Next steps

To learn more about the integrated technologies presented in this use case, see the following resources: