Authentication to LeanIX Services

Learn how to authenticate to LeanIX services.

Overview

In this guide, you will learn how authentication to LeanIX services works.

To authenticate your requests, follow these key steps:

  1. Obtain an API token by creating a Technical User.
  2. Encode the API token to Base64 format.
  3. Using the Base64-encoded string, obtain an access token.
  4. Make authenticated requests to services by including the access token in the Authorization header.

📘

Before you begin, make sure that you know your LeanIX subdomain. You can copy your subdomain value from the Workspace URL. To learn more, see Base URL.

Authentication Flow

LeanIX employs the OAuth 2.0 protocol for user authentication across all available APIs. In the image below, you can see how the authentication process works for an example API request.

LeanIX OAuth 2.0 flow

LeanIX OAuth 2.0 Flow

Step 1: Obtain an API Token

To request an access token, you need to obtain an API token first. As an administrator, you can generate an API token by creating a Technical User.

🚧

The API token is shown only once. Make sure you store it securely.

How to securely use an API token?

Treat an API token like a password or other sensitive credentials.

Here are some best practices to securely use API tokens. This list is non-exhaustive.

  • Don’t share API tokens with anyone who shouldn’t be using them.
  • Delete unnecessary API tokens by deleting Technical Users.
  • Replace API tokens periodically.
  • Store API tokens securely, for example, use secrets management tools.
  • Securely use API tokens in your code.
  • Transfer API tokens securely.
  • Set up monitoring and auditing to detect and respond to any unauthorized access.

Step 2: Encode the API Token

Use a programming language to encode your credentials to Base64 format. Base64 encoding serves as a method to ensure secure transmission of sensitive information.

Create a string in the format apitoken:{API_TOKEN}, where {API_TOKEN} is the token that you obtained in the previous step.

The following example shows how to generate a token in a shell.

echo -n 'apitoken:{API_TOKEN}' | base64

In the response, you get a string encoded in Base64, as in the following example.

YXBpdG9rZW46SnFjU2ZlQjdzTzNCZDlkRURjU09YZmpzNkc2T1JDc1Q2RzlmQkhDYw==

Step 3: Obtain an Access Token

Now that you have your Base64-encoded string, you can obtain an access token.

Request an Access Token

To request an access token, make a POST request to the following endpoint:

https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token

The authentication endpoint employs the Basic authentication scheme. Use the Base64-encoded string as the credentials, and set the grant_type to client_credentials.

The following examples show how to make a request to obtain an access token:

curl -X POST https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token \
	-H "Authorization: Basic {BASE64_ENCODED_STRING}" \ 
	-d "grant_type=client_credentials"
const axios = require('axios');
// base64Credentials is the base64 encoded string you generated in Step 2.1
const base64Credentials = "YXBpdG9rZW46SnFjU2ZlQjdzTzNCZDlkRURjU09YZmpzNkc2T1JDc1Q2RzlmQkhDYw==";
var instance = "https://{SUBDOMAIN}.leanix.net";
const tokenEndpoint = "https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token"

// Step 2: Make a POST request to obtain the access token
const getToken = async () => {
  try {
    const response = await axios.post(
      tokenEndpoint,
      'grant_type=client_credentials',
      {
        headers: {
          Authorization: `Basic ${base64Credentials}`,
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );

    // Step 3: Receive and use the access token
    const accessToken = response.data.access_token;
    console.log('Access Token:', accessToken);

    // Now you can use the accessToken in your API requests
  } catch (error) {
    console.error('Error obtaining access token:', error.message);
  }
};
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials");
Request request = new Request.Builder()
  .url("https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token")
  .post(body)
  .addHeader("authorization", "Basic YXBpdG9rZW46SnFjU2ZlQjdzTzNCZDlkRURjU09YZmpzNkc2T1JDc1Q2RzlmQkhDYw==")
  .build();

Response response = client.newCall(request).execute();
import requests
from requests.auth import HTTPBasicAuth

# timeout is set to 20 seconds
timeout = 20
# base64_credentials is the base64 encoded string you generated in Step 2.1
base64_credentials = 'YXBpdG9rZW46SnFjU2ZlQjdzTzNCZDlkRURjU09YZmpzNkc2T1JDc1Q2RzlmQkhDYw=='
api_url = 'https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token'

# Step 1: Create a Base64-encoded string for Basic Authentication
credentials = f"{username}:{password}"
encoded_string = base64.b64encode(credentials.encode()).decode()

# Step 2: Make a POST request to obtain the access token
try:
    headers = {
        'Authorization': f'Basic {base64_credentials}',
        'Content-Type': 'application/x-www-form-urlencoded',
    }

    data = {
        'grant_type': 'client_credentials',
    }

    response = requests.post(api_url, headers=headers, data=data, timeout=timeout)

    # Step 3: Receive and use the access token
    if response.status_code == 200:
        json_response = response.json()
        access_token = json_response['access_token']
        print(f"Access Token: {access_token}")

        # Now you can use the access token in your API requests
    else:
        print(f"Error obtaining access token. Response code: {response.status_code}")

except Exception as e:
    print(f"Error: {str(e)}")

Review the Response

The response from the https://{SUBDOMAIN}.leanix.net/services/mtm/v1/oauth2/token endpoint includes your access token. Handle the response according to your programming language or tool.

Example response:

{
 "scope":"",
 "expired":false,
 "access_token":"eyJhbGciOiJSUzI1NiJ9.eyJz [...] ssqaPSA",
 "token_type":"bearer",
 "expires_in":3599
}

The access_token is returned in JWT (JSON Web Token) format. JWTs are encoded tokens that carry information in a compact and self-contained manner. In the context of OAuth 2.0, access tokens are often JWTs.

Tokens are signed with a private key, enabling our APIs to validate their authenticity. The signing process ensures that the token has not been tampered with and comes from a trusted source.

You can decode your access token using tools such as JWT.IO. Once you have decoded your token, you can view the token details, such as:

  • Permissions: Information about the user's permissions or scope, indicating what actions or resources the token holder is authorized to access.
  • Expiration time: The validity duration of the access token in seconds is specified in expires_in. The access token is valid for 3600 seconds, which is equivalent to one hour.

📘

OAuth 2.0 access tokens often have a limited lifespan for security purposes. By setting an expiration time, the system can automatically revoke access after a certain period, minimizing the risk of unauthorized access if the token is compromised. This practice is part of the OAuth 2.0 security model to ensure that tokens are regularly refreshed, requiring the client to reauthenticate to obtain a new valid token.

Step 4: Make Authenticated Requests to Services

After obtaining an access token, you can use it to make authenticated requests to your service.

To authorize your request, insert your access token into the Authorization header. Be sure to include the Bearer prefix to specify the token type.

As an example, let's fetch a list of Applications, internally referred to as services, from the IT Inventory of a Workspace.

📘

Reuse the access token in your API requests within the token lifetime. Do not request new access tokens while the current token is still valid.

Repeatedly requesting new tokens without necessity may lead to security vulnerabilities and unnecessary load on the authorization server. Adhere to the token expiration time and only request a new token when necessary.

In the following example request, the access token (eyJhbGciOiJSUzI1NiJ9.eyJz [...] ssqaPSA) is shortened. When implementing this in your applications, ensure that you use a complete and unaltered access token.

curl -H "Authorization: Bearer {ACCESS_TOKEN}" \
	https://{SUBDOMAIN}.leanix.net/test/api/v1/services
const axios = require('axios');

// Replace {SUBDOMAIN} with your actual subdomain
const url = 'https://{SUBDOMAIN}.leanix.net/demo/api/v1/services';
const accessToken = 'eyJhbGciOiJSUzI1NiJ9.eyJz [...] ssqaPSA'; // Replace with your actual access token

// Step 2: Make a GET request to the /v1/services API endpoint
axios.get(url, {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
})
  .then(response => {
    // Process the response as needed
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://{SUBDOMAIN}.leanix.net/test/api/v1/services")
  .get()
  .addHeader("Authorization", "Bearer eyJhbGciOiJSUzI1NiJ9.eyJz [...] ssqaPSA")
  .build();

Response response = client.newCall(request).execute();
import requests

timeout = 20
url = 'https://{SUBDOMAIN}.leanix.net/test/api/v1/services'
headers = {'Authorization': 'Bearer eyJhbGciOiJSUzI1NiJ9.eyJz [...] ssqaPSA'}

response = requests.get(url, headers=headers, timeout=timeout)

# Process the response as needed
print(response.text)

Related Information

Configuring Authentication to LeanIX APIs in Postman