Exploring the full potential of the Logto Management API
Tags: webdev, programming, identity, opensource
Published: 2024-06-20 01:34:43

In this article, we will reemphasize the definition of the Logto Management API, explain how it works, and showcase typical scenarios to boost your productivity and unlock more use cases.

---
As an infrastructure service, we strive to make using our Logto Management API easier and faster. We've recently updated our guides and tutorials. In this article, we will reemphasize the definition of the Logto Management API, explain how it works, and showcase typical scenarios to boost your productivity and unlock more use cases.

# What is Logto Management API

The Logto Management API is a powerful set of pre-built APIs that gives developers full control to customize their implementation to suit their product needs and tech stack.

It is listed in the API resource list and cannot be deleted or modified. Everything you can do in the Logto Admin Console can also be done with the Logto Management API.

It identifier is in the pattern of `https://[tenant-id].logto.app/api`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccgsh0vqlfli6nab1d6o.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5j8lrkcg3ya4j5tz5r4.png)

It includes `all` permissions by default. As Logto grows, we will continue to make permissions more granular.

With the Logto Management API, you can access Logto's robust backend services, which are highly scalable and can be utilized in a multitude of scenarios. To learn about the APIs that are available, please visit [Logto API references](https://openapi.logto.io/).

# Typical scenarios for using management API

Our developers have implemented many additional features using our Management API. We believe that our API is highly scalable and can support a wide range of your needs. Here are a few examples of scenarios that are not possible with the Logto Admin Console but can be achieved through the Management API.

### Implement user profile with your custom UI


Logto currently does not provide a pre-built UI solution for user profiles. We recognize that user profiles are closely tied to business and product attributes. While we work on determining the best approach, we suggest using our APIs to create your own solution. For instance, you can utilize our interaction API, profile API, and verification code API to develop a custom solution that meets your needs. We've prepared a dedicated page [User Profile](https://docs.logto.io/docs/recipes/user-profile/) for tutorials and guides.

An interesting example is that the Logto Cloud user profile feature is built using the Logto Management API.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gz8dbgeklxukt1ofjgsm.png)

### Implement organization management with your custom UI

If you're using the [organization](https://docs.logto.io/docs/recipes/organizations/) feature to build your multi-tenant app, you might need the Logto management API for tasks like org invitations and member management.

Similarly, Logto Cloud invitation and collaboration feature is built using the Logto Management API too.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l613otdjih4za5dd1cff.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mw36c04cu9euwu3rdika.png)
To extend that case, for your SaaS product, where you have both admins and members in the tenant, the Logto management API can help you create a custom admin portal tailored to your business needs. Check out [this](https://docs.logto.io/docs/recipes/organizations/configuration/#configure-via-management-api) for more detail.


### Advanced user search
The Logto Admin Console supports basic search and filtering functions. If you need more advanced options to tailor your user management service to your business needs, you can use the Logto Management API. It supports advanced search options, such as:

1. Fuzzy search
2. Exact match
3. Case sensitivity
4. Specify fields

Check out our [Advanced User Search](https://docs.logto.io/docs/recipes/manage-users/advanced-user-search/) tutorials and guides.

### Utilize Logto's logs to construct your own services
Logto's audit log allows you to easily monitor user activity and events. It provides a strong foundation for various user management and health check business scenarios.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lggofp6rd9o7sixgcrqv.png)

By utilizing the management API, you can access real-time audit log data. This allows you to design your own schema model and dashboard using the log data obtained from Logto.

### Migrate and import users to Logto
Using the Management API can easily help you import user data, especially you want to do a [migration](https://docs.logto.io/docs/recipes/migrations/) to Logto.

After you prepare the user data and set up [password hashin](https://docs.logto.io/docs/recipes/migrations/#password-hashing)g and the user schema, set up the Management API connection and we'll call create user API to import the user data. To learn more about the migration, check out this document.

# How to access Logto Management API
### Create a M2M app

Select the M2M app type and start the creation process. After creation, you'll be directed to a module where you can assign a machine-to-machine role.

After providing a name and description, you'll see a module that asks you to assign a role. This module includes all M2M roles, roles indicated by a Logto icon means that these roles include Logto management API permissions.

Assigning M2M roles include Logto management API permissions for your M2M app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb90da19uhsm4g02avxt.png)

### Why using machine-to-machine and assigning machine-to-machine roles?
Why does Logto allow M2M (Machine-to-Machine) communication to call the Logto Management API instead of using API keys?

Logto tackles customer identity management and strictly follows open standards like OAuth 2.0 and OpenID Connect. M2M tokens offer secure server-to-server interactions with specific scopes, providing better security than static API keys. Unlike API keys, which don't expire and pose a higher risk if compromised, M2M tokens have defined expiration times, limiting the window for potential misuse.

In Logto, we use role-based access control (RBAC) to protect and manage access to the Logto Management API. This entity diagram shows how it works.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5w1h3o3maghaqcv8mee.png)

The relationship of permissions, API resources, roles and machine-to-machine application.

### Fetch an access token

#### Basics about access token request

M2M app makes a `POST` request to the token endpoint to fetch an access token by adding the following parameters using the `application/x-www-form-urlencoded` format in the HTTP request entity-body:

- **grant_type**: must be set to `client_credentials`
- **resource**: the resource indicator you want to access
- **scope**: The scope of the access request

And you also need to include your M2M credentials for the token endpoint to authenticate your M2M app. This is achieved by adding a `Authorization` header using [Basic authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization#basic_authentication), where username is the App ID, and password is the App Secret.

You can find the App ID and App Secret from your M2M applicaiton details page:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ui87lkabt090k21altsg.png)

An example of the Logto Management API access token request is:

```
POST /oidc/token HTTP/1.1
Host: you-tenant-id.logto.app
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
resource=https://you-tenant-id.logto.app/api
scope=all
```
#### Fetch access token for Logto Management API
Logto provides a built-in “Logto Management API” resource, it's a readonly resource with the `all` permission to access Logto Management API, you can see it from your API resource list. The resource API indicator is in the pattern of `https://{YOUR_TENANT_ID}.logto.app/api` , and this will be your resource value used in the access token request body.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzjwfpe09mv8n9j0q92q.png)

Before accessing Logto Management API, make sure your M2M app has been assigned with M2M roles that include the `all` permission from this built-in “Logto Management API” resource.

Now, compose all we have and send the request:

```
const yourTenantId = 'your-tenant-id';
const tokenEndpoint = `https://${yourTenantId}.logto.app/oidc/token`;
const applicationId = 'your-application-id';
const applicationSecret = 'your-application-secret';

const fetchAccessToken = async () => {
  return await fetch(tokenEndpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${Buffer.from(`${applicationId}:${applicationSecret}`).toString(
        'base64'
      )}`,
    },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      resource: `https://${yourTenantId}.logto.app/api`,
      scope: 'all',
    }).toString(),
  });
};
curl --location \
  --request POST '<https://$>{your-tenant_id}.logto.endpoint/oidc/token' \
  --header 'Authorization: Basic ${your_auth_string}' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'grant_type=client_credentials' \
  --data-urlencode 'resource=https://${your_tenant_id}.logto.app/api' \
  --data-urlencode 'scope=all'
```

> 💡 When you're interacting with Management API, use the default Logto endpoint `https://[your-tenant-id].logto.app/oidc/token` to grant the Access Token.


#### Token response
A successful response body would be like:

```
{
  "access_token": "eyJhbG...2g", // JWT format access token, used for accessing the resource
  "expires_in": 3600, // Token expiration in seconds
  "token_type": "Bearer", // Auth type for your request when using the Access Token
  "scope": "all" // "all" for Logto Management API resource and
}

```

> 💡 Logto does not currently support the M2M app to represent a user. The `sub` in the access token payload will be the App ID.

### Access Logto Manage API using Access Token
You may notice the token response has a `token_type` field, which it's fixed to `Bearer`. Thus you should put the Access Token in the `Authorization` field of HTTP headers with the Bearer format (`Bearer YOUR_TOKEN`).

Now you can access the Logto Management API by reqeusting the Logto Managemetn API endpoint `https://[your-tenant-id].logto.app/api`, to get all applications in Logto

```
curl --location \
  --request GET 'https://your.logto.endpoint/api/applications' \
  --header 'Authorization: Bearer eyJhbG...2g'# Access Token
```

# Related resources

Here are some related resources that delve into our previous insights and strategies for using the Logto Management API. These materials cover various aspects, including best practices, implementation tips, and use cases, to help you make the most out of the Logto Management API for your projects.

- [Machine-to-machine quick start](https://docs.logto.io/quick-starts/m2m/)
- [Interact with Management API](https://docs.logto.io/docs/recipes/interact-with-management-api/)
- [Logto API references](https://openapi.logto.io/)
- [Use Logto Management API: A step-by-step guide](https://blog.logto.io/management-api/)

{% cta https://logto.io/?ref=dev %} Try Logto Cloud for free {% endcta %}