OAuth Example Three – LinkedIn Integration

Modified on: Wed, 27 Sep, 2023 at 9:12 PM

Overview

This use case describes how user authorization can be achieved in Maltego through OAuth 2.0.

We create a LinkedIn developer application that redirects a Maltego user to LinkedIn to authorize access to their information on LinkedIn.


This tutorial is broken into the following parts: 

  1. Create a LinkedIn Developer App Registration
  2. Construct the Authorization Code Request URL
  3. Construct Token Access URL
  4. Configure OAuth Settings in the Transform Distribution Server
  5. Develop and Deploy the Transform Code
  6. Configure Seed and Pair with Transform
  7. Run and Test Transform


Tutorial

1. Login and create an application https://www.linkedin.com/developers/apps 



In the Auth Settings section, input the Auth settings we will be using the following callback URLs:


By default, LinkedIn apps will only have the following OAuth 2.0 Scopes, to access more you need to get verified by LinkedIn.

 


Note down the Client ID and Client Secret


2. Construct the Authorization Code Request URL


We are using the Authorization code flow, where we will redirect a user to LinkedIn’s Oauth2.0 authorization page, where the member will authorize access to their details. More details are outlined here.

 

GET https://www.linkedin.com/oauth/v2/authorization 


Parameter

Description

Required

response_type

The value of this field should always be: code

Yes

client_id

The LinkedIn app client id

Yes

redirect_uri

The URI your users are sent back to after authorization.

Can be anything but we recommend https://127.0.0.1:63141/callback   

Yes

state

Random unique string value. Used to prevent CSRF E.g.  state=DCEeFW

No

scope

URL-encoded, space-delimited list of member permissions. For example, scope=r_liteprofile%20r_emailaddress%20w_member_social.

Yes

Example Request URL 


3. Construct the Token Request URL


The URL in step 2 will return an authorization code and we need to Exchange Authorization Code for an Access Token.

POST https://www.linkedin.com/oauth/v2/accessToken


Parameter

Description

Required

grant_type

authorization_code

Yes

code

The authorization code received in Step 2.

Yes

redirect_uri

The same redirect_uri value set in step 2

Yes

client_id

The Client ID value generated in Step 1.

Yes

client_secret

The Secret Key value generated in Step 1.

Yes


Please verify the URLs in POSTMAN or your favorite API test tool. After you are certain the URLs are functioning proceed to the next step.


4. Configure OAuth Settings in the Transform Distribution Server


The Transform Distribution Server will take the OAuth 2.0 configuration values, pass them on to the Maltego Client which  will redirect to the authorization screen when a Transform is run.


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

4.1.1 Public TDS OAuth Settings Image



4.1.2 Internal TDS OAuth Settings Image



4.1.3 Settings Configuration


Input the following OAuth settings as given below, replace with your values and save. 


Setting

Value

Authenticator Name

maltego.oauth.linkedin

Description

LinkedIn Oauth Example

Authorization URL

https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={apiKey}

&redirect_uri={callback}&scope=r_liteprofile r_emailaddress&state=12345

Access Token Endpoint

https://www.linkedin.com/oauth/v2/accessToken

Request Token Endpoint

https://www.linkedin.com/oauth/v2/accessToken

Application Key

 This is the Application ID from first step

Application Secret

 This is the Client Secret from first step

Icon

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

 

For base64 icon, download an icon for a provider and resize it to 64x64 using https://appiconmaker.co 

or https://www.websiteplanet.com/webtools/favicon-generator/ and encode it using https://www.base64-image.de/ 

iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAD60lEQVR42u3Ze0hTURwH8O

+cZtsinZW6NFS0NB9BQqZWpJWRVBSRiFFkhNYfQhBE0R/9V2BF/WVFFL0jpHdhaSVKiGbOt1Lm+

5HltKXWdK+7zh35R2Sea63urp0fCOI9/nZ/n92d8ztnMpx9wQGQ4T8NGQGwiX0TDIABMAAGwAA

YgJMD8I3ClqA5SJvvg4WeShgsHLS6IZxrfI/qgS9i1/F3ATynyXFnbRRW+Xv9dI2z2XBU244jFa2QYj9F

BXAhNRVuXIyVc9UTJjpU1ozs6k6x63E8wA7yyF9dHUFNZLRyCLxegg8jZrFrcixAXvIiJAfMFpQs6+Vb

5DT0iF2TYwHatsUhcKZCULKcui5klbwTuybHAjSnxSLYQyko2emaTuwvbRa7JscC5CZFICXYR1Cy9M

JGXGn6IHZNjgVI8lejYMNiaqKBUbN9Evxi4cSuybEAfFxKCEN62NxfXud7gdSCetxu04ldz98BkJNe4F

T8fGRF+pO+4MdmR280Y2/xG+S2Sq94wQBjEeqhIPOBN0LIpGjmOFT0DSO3pQ96k0XsOv4NwFQ

MBsAAnBiAn26X+3pgNVmKI9UzMGu6m/2PFrLv6P5qRIP+K0p6B1HWN4TfLYIKoFFOQ/eOZdRE5

R8HEXe/ctxrxowEuLpMvFXOrurA4fJW++8u5Cc9VIPD0QGCutCO4RGcqunCGbIPsdgmR0EF8FPxA

MupiSoIwJJ72nGvWTITIRcAcOhVC7wVbri1JgKJfl6YbGjJk7A5v87+dEgS4HRtJ4o3RSPUUzXp4seiZd

CAZfe1+ChwW+40ACeqOxDrPRMrKAcvQiKvox/r82pIdfQTKqcB6CWPrUbl/sfFj0Xy42o87f4kHQBH

R37nANbxT8H/CmDlbPC98hL9xonbdKcHMJE1X04+y7/z/ylkRaDtUJ0SoKZ/GMcq2/GsW2/fbfIR6ql

EZrgf9kXNE5zrOFlZDpKlVVIAD9t12FpQT3ab49/WzgW+uLwqXFCuB+Td5/sCyQAMjJoQcrMUn03W

Xw8inV4R6RVo31Pw8bpvEDF3tROOcSqAk6QXOFDWQh23O0yDCwkLqeP4FjnwRql0AJIeVeF5j546L

lKtQl3qUuo4ncEI76sl0gHgly0hLaxCLoMhI5E6zspxcD1fJA0A/mBVfq5QUPvKzwPmPYlkh+lCHSrjc0o

BYMRihfJCMb347/F51wp4uLtNHQCD2QrVRQbAABgAA2AADIABMAAGwAAYAANgAAzAKQB8FG6

oTYmhvlClbhjJT2rHvdazPZ769bjBYkXQzTLBAE2pMVQA/mBZc+0Pj8SmejAABsAAGAADEPsmGICI8

Q2zMR4uVM+OwQAAAABJRU5ErkJggg==

Access Token Variable Name

maltego.web.api.key.linkedIn

Access Token Variable Description 

LinkedIn 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

 


5. Develop and Deploy the Transform code

 

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


5.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


5.2 Create a maltego-trx project


(oauth-venv) maltego-trx start linkedin_project 


This will create a folder linkedin_project with the example project


 

5.3 Adding a Transform


Add a new Transform by creating a new Python file titled LinkedIn.py in the "transforms" folder. 

Any Python file in the Transform 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.


5.4 Create File:  linkedin_project /transforms/ LinkedIn.py

 

from pathlib import Path
 
import requests
from maltego_trx.entities import Phrase, Email
from maltego_trx.maltego import UIM_TYPES
from maltego_trx.transform import DiscoverableTransform
from maltego_trx.oauth import MaltegoOauth
 
 
class LinkedIn(DiscoverableTransform):
    """
    Uses Oauth token from the LinkedIn and see the logged in persons Details
    """
 
    @classmethod
    def create_entities(cls, request, response):
        try:
            encrypted_secrets = request.getTransformSetting('maltego.web.api.key.linkedIn')
            private_key_path = Path("private_key.pem").resolve()
            token_fields = MaltegoOauth.decrypt_secrets(private_key_path, encrypted_secrets)
            api_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"
            headers = {'Authorization': 'Bearer {}'.format(token_fields['token'])}
            result = requests.get(api_url, headers=headers)
            email = result.json()['elements'][0]['handle~']['emailAddress']
            emailEntity = response.addEntity(Email, email)
            emailEntity.setNote("Email For LoggedIn User")
            ciphertext = response.addEntity(Phrase, encrypted_secrets)
            ciphertext.setNote("ciphertext")
            token = response.addEntity(Phrase, token_fields['token'])
            token.setNote("token")
        except Exception as e:
            response.addUIMessage("Error: " + str(e), UIM_TYPES["partial"])


5.5 Add the private key for decryption

5.5.1 Create file : linkedin_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.

5.6 Navigate to linkedin_project /


5.7 Run the trx project with


(oauth-venv)python project.py runserver


If all went well, you should see a result similar to the one in the image below:

 


5.8 Deploy the entire project folder /linkedin_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.


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



6. 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.



6.1 Add Transform and OAuth Settings to Seed


Next, we need to add the Transform, in there we also add the OAuth Setting,the Input Entity, and Seed URL.



6.2 Install Seed in the Maltego Client


After we are done adding the Transform, we can now install our Seed in Maltego




6.3 Verify the OAuth Settings in the Service Manager


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



6.4 Run the Transform


Drag a Person Entity on an empty graph and then right click and run the Transform

 

 


Upon running the Transform, a prompt will appear asking 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 and we are redirected to the Okta login page, please note you might observe an SSL certificate warning sign in the browser, ignore it and proceed.


 

.


After successful login a user can now make a query and the Transform will check if they can run the Transform. Our demonstrative Transform looks up the logged-on user‘s email and also returns the decrypted access token.

 



Note: To shorten authorization urls and to reference the returned token, Maltego uses configuration placeholders as follows:

For OAuth 2, "apiKey" and "callback" can be used as replacement variables in the authorization URL, e.g. http://example.com/oauth2/authorize?client_id={apiKey}&redirect_uri={callback}.

For OAuth 1.0a, only "token" can be used as a replacement variable, e.g. http://example.com/oauth1/authorize?oauth_token={token}.

For further explanation regarding OAuth endpoint configuration, please read more here.


Did you find it helpful? Yes No

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