OAuth Example Two - Okta OpenID Connect Integration

Modified on: Thu, 29 Oct, 2020 at 11:53 AM

Overview

This use case describes how user authorization can be achieved through OAuth 2.0 via scoped access tokens, as well as user authentication via OPENID Connect. To achieve this, we will be integrating Maltego with the Okta OpenID Connect & OAuth 2.0 API


Use Case

We will configure an Identity Management Application (iDM) on Okta which will be responsible for authenticating users through OPENID Connect and OAuth. We will integrate this IDP application with Maltego and demonstrate how identity management can be done through OAuth in the Maltego ecosystem.


Finally, we will create a Transform that will require initial sign-in on our iDM provider website [Okta] and will return varying information depending on the user access rights.  There will be two user groups, free and paid users.


After creating an Okta developer application, we will add users and provide them with varying permissions. Configure OAuth on the apps to allow the Maltego client to redirect users to the Okta website to login, Okta will return a token to Maltego which can then be used by the Transform to make queries. 


We will then show how developers can create Transforms which use the retrieved access token to verify the access rights allocated to a user.


This tutorial is broken into the following parts:

  1. Sign up and create an Okta Account
  2. Create the Okta Developer App Registration
  3. Create User Groups
  4. Create and Assign Users to the Okta App
  5. Create a Group Claim
  6. Verify Okta Authorization configuration
  7. Configure OAuth Settings in the Transform Distribution Server
  8. Develop and Deploy the Transform code
  9. Configure Seed and pair with Transform
  10. Run and Test Transform


Tutorial


1. Signup for an Okta account via https://developer.okta.com/signup/ 

2. Login and create an application

 


In the Create New Application window, select Web and click Next



In the Application Settings section, input the OAuth settings. We will be using the following

Callback URLs:


https://127.0.0.1:63141/callback    

http://127.0.0.1:63141/callback


Allowed OAuth Grant Types: Authorization Code



Take note of you Client ID and Client Secret.


3. . Create User Groups

3.1 Create two groups free and paid



4. Create Users and add to Groups

4.1 Add a user and assign to the free group



4.2 Add another user and add to the paid group



5. Create a custom token claim


Tokens contain claims which are statements about the subject or another subject, for example; name, role, email address or the groups that they belong to. We will need to add a claim to include the user group information in the access token. E.g.

 

  "scp": [
    "openid"
  ],
  "sub": "test.maltego@outlook.com",
  "groups": [
    "Everyone",
    "free"
  ]


Navigate to API -> Authorization Servers -> Default

 


5.1 Add Claim for ID Token


Add a new Claim named "groups"This claim will have a value type groups and we will use a wildcard regex, this means if the groups claim is set for an authorization server it will return all the user groups the person belongs to. We also set that this claim will only be available when the openid scope is requested. As shown in the image below:

 

5.2 Add Claim for Access Token


Repeat the process, but for the include in token typesetting choose Access Token



6. Verify configuration


Okta provides a token preview which simulates how the token will look like when a user authenticates correctly. Confirm that the group is shown in the token JSON as shown below.

 


7. Configure OAuth Settings in the Transform Distribution Server

7.1 Open your iTDS server or to the public TDS and create an account. Open OAuth Settings

7.1.1 Public TDS OAuth Settings Image

7.1.2 Internal TDS OAuth Settings Image



7.1.3 Settings Configuration


SettingValue
Authenticator NameiTDS Azure OAuth
DescriptionAzure OAuth Config
VersionOAuth 2.0
Access Token Endpointhttps://login.microsoftonline.com/common/oauth2/v2.0/token
Request Token Endpointhttps://login.microsoftonline.com/common/oauth2/v2.0/authorize
Authorization URLhttps://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={apiKey}&response_type=code&redirect_uri={callback}&response_mode=query&scope=profile,openid,User.Read,Contacts.Read

Application Key

This is the Application ID from the step 2

Application Secret

This is the Client Secret from step 2

Icon

Please note to use a very small resolution image. The Maltego client does not accept very large b64 images. Use to 64X64 or less

iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABzUlEQVQ
4T5WTSyhEURjH/9cwYjEMgwlRJpJHnrHxyiMLj2ZhKSVFE7GQkqwsLNh5bEjZ
WCllkDyilLzyWomM3Fh4lMd4m3GP7jHndube2biL0+073/c73/l//yMQQgj++
ckFgqdGkAGMwILyHkvik33FKIAVqBuRCIHj+RtJoYEKkIfL/wpAveGWCOrXr1A
Q7o+WdDMCdH4UQos8HWoAPKRuVcSc+ILuBB2K4sJQaolS7q3RQH362dM
XkqfPkB8ZjIiXG8QbgzFUlaUA2FUpSPJowLc1cHyP7t0bdKabMLm+C4PeH47
OKt8ANgV+AgV2BzZv39GfaUSPfYseeNRagQxzqGY6GhHvP9yInjrBDwHGck
PQPLNDAX1lqegtSdHooBnj5OkjmjaukRiix4HVgpjBeTg/XciONmLPVq5Mge
ng1YEctC6LmBWdaEwyYqI4Fh0LhxjZPqf5Ylc1Yg1BXhAvgEQA68ol3lwS2tN
MqI034OTOidThJdr6aE02bHkWbx14Edl8XZKEtYs7xZhtc4dwPLyiMtGMxYZ
CGme5Gg3kk96+3bDZ9zXO0+t0GLfmQBD+Ziav1Ae8B9gGbxZ1jH8zymtk
PlD7nfeHL+gv3H7Uzc9uAmYAAAAASUVORK5CYII
Access Token Variable Namemaltego.web.api.key.azure
Access Token Variable DescriptionAzure OAuth Token

Public Key

For the key pair, you can generate your own pair or use the one provided by Maltego and copy it a secure place. We do have access to your Private Key
Private Key


8. Develop and Deploy the Transform code


We will be using the Maltego open source maltego-trx library to develop the demo Transform. Upon completion this will need to be deployed to a publicly accessible server such as a VPS or VM.  You need to have Python3 and pip installed.


8.1 Install the Prerequisite Software

python3 -m pip install --user virtualenv
python3 -m venv oauth-venv 
(oauth-venv) pip install maltego-trx
// install version 1.3.7+ only

8.2 Create a maltego-trx project


(oauth-venv) maltego-trx start okta_openid_project

This will create a folder okta_openid_project with the example project



8.3 Adding a Transform


Add a new Transform by creating a new python file titled OktaOpenID.py in the "transforms" folder. 

Any Python file in the transforms folder whose class name matches the filename and the class inherits from Transform, will automatically be discovered, and added to your Transform server.


Add the following files and the corresponding code.


8.4 Create File: okta_openid_project /transforms/OktaOpenID.py


import base64
from pathlib import Path

import requests
from maltego_trx.entities import Phrase
from maltego_trx.maltego import UIM_TYPES
from maltego_trx.oauth import MaltegoOauth
from maltego_trx.transform import DiscoverableTransform


class OktaOpenID(DiscoverableTransform):
    """
    Decrypts Okta Access Token and check if it is valid and verifies if a user belongs to free or paid groups
    """

    @classmethod
    def create_entities(cls, request, response):
        # variables for making a POST verification API call to OKTA
        introspect_url = "https://dev-617245.okta.com/oauth2/default/v1/introspect?token="
        client_id = "0oaopc9t1IQ5q8RMR4x6"
        client_secret = "-xetW-_rFMlCm4GgaK6XF2GtD648-ugly7OwGD-w"
        payload = {}
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        b64_auth_bytes = base64.b64encode((client_id + ":" + client_secret).encode("utf-8"))
        b64_encoded_auth = str(b64_auth_bytes, "utf-8")

        try:
            # get the encrypted token from the client, this is the Access Token Variable Name set in the iTDS
            encrypted_secrets = request.getTransformSetting('maltego.web.api.key.okta')
            private_key_path = Path("private_key.pem").resolve()
            token_fields = MaltegoOauth.decrypt_secrets(private_key_path, encrypted_secrets)
            token = token_fields['token']
            token_verification_url = introspect_url + token + "&token_type_hint=access_token"
            headers['Authorization'] = 'Basic ' + b64_encoded_auth
            result = requests.request("POST", token_verification_url, headers=headers, data=payload)
            # Check if Token is Valid
            active = result.json()['active']
            if active:
                cls.checkUserType(result.json(), response)
            else:
                response.addUIMessage("Token Expired please login again", UIM_TYPES["partial"])
        except Exception as e:
            response.addUIMessage("Error" + str(e), UIM_TYPES["partial"])

    @classmethod
    def checkUserType(cls, token_payload, response):
        groups = token_payload['groups']
        if "paid" in groups:
            text = "paid user: " + str(token_payload)
            response.addEntity(Phrase, text)
        elif "free" in groups:
            text = "free user: " + str(token_payload)
            response.addEntity(Phrase, text)
        else:
            text = "unknown user group"
            response.addEntity(Phrase, text)
8.5 Add the private key from step 7.1.3 for decryption

8.5.1 Create file : okta_openid_project /private key.pem

    Add the contents of the private key to this PEM file. It is possible to just upload/save the actual PEM file to this location if

    you have it as a PEM file.


8.6 Navigate to okta_openid_project /

8.7 Run the maltego-trx project with:

 

(oauth-venv)python project.py runserver


If all went well, you should see something like this:

 


8.8 Deploy the entire project folder / okta_openid_project to a remote VPS/VM/Dockerized environment. 

More details on how to deploy for production can be found here for standard web deployment and here for Docker containerized deployment. The simplest method for this tutorial is to upload the folder to a remote server through git or ftp.


8.9 Navigating to your VPS IP http://<ip-address>/run/oktaopenid in a browser you should the following output. If it doesn’t not work check that you have opened the necessary, port on the firewall.



9. Configure Seed and pair with Transform


Now that we have our Transform up and running, we need to create a Seed to distribute the Transform. The TDS will generate a random alphanumeric Seed name for you, but you can also use one of your choosing.



10.1 Add Transform and OAuth Settings to Seed.

Next, we need to add the Transform, we also add the OAuth setting and the Input Entity and Seed.

 


10.2 Install Seed in the Maltego Client

After we have added the Transform, we can now install our Seed in Maltego.



10.3 Verify the OAuth Settings in the Service Manager

We can view the OAuth Authenticator settings in the Service Manager by selecting the Manage Services options in the Transforms menu. Cross-check that the protocol set in step 2.3 is the same as those shown here. The settings the Service Manager correspond should correspond to the callback URL set in the provider Application.



10.4 Run the Transform

Drag a Phrase Entity onto an empty graph, right click and run the Transform.


 

 


Upon running the Transform, a prompt will appear asking you to sign in to use the Transform. Click Sign In. A browser page will be opened with the URL http://127.0.0.1:63141/signin. We are redirected to the Okta login page, please note you might observe a warning sign in the browser, ignore it and proceed.


 

The application we created will accept logins from the users registered with Okta and added to the application we created earlier. In an organizational setup the privileges will be set by the admin.



After successful login, a user can now make a query and the Transform will check if they are allowed to run the Transform. Our example Transform checks the group a user belongs to. E.g. when a user in the free group logs in, they would only receive the details applicable to free users.


 

When the token expires, you will see a warning message that informs the user that they have to sign in again.

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.