> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dbiz.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gọi API giữa các dịch vụ bằng client credentials

> Dịch vụ gọi dịch vụ không có người dùng thì lấy token bằng client credentials của Keycloak. Xem cấu hình client service account và cách xin token.

Khi một dịch vụ gọi API của dịch vụ khác mà không nhân danh người dùng nào, dịch vụ đó lấy token bằng client credentials của Keycloak. Token mang danh tính của chính client (service account), không phải của người.

## Cấu hình cần cung cấp cho client

| Thuộc tính | Giá trị |
| - | - |
| Client authentication | On (client confidential) |
| Service accounts | On |
| Standard flow, Direct access, Implicit, Device | Off |
| Redirect URIs, Web origins | Để trống |
| Role của service account | Tối thiểu cần thiết cho việc dịch vụ làm |
| Audience mapper | Trỏ tới API đích để API đó kiểm được `aud` |

> [!NOTE]
>
> Client service account cần thêm một bước chuẩn bị phía nền tảng. Báo trước khi gửi yêu cầu.

## Xin token

```bash client-credentials.sh theme={null}
curl -s -u "<svc-client-id>:${CLIENT_SECRET}" \
  -d grant_type=client_credentials \
  https://<id-host>/realms/<realm>/protocol/openid-connect/token
```

Phản hồi có `access_token` và `expires_in`. Cache token và xin lại trước khi hết hạn, thay vì xin mới cho mỗi request.

## API đích nhận biết token máy

Token của service account có `preferred_username` dạng `service-account-<svc-client-id>` và `azp` là client đó. API đích nên phân biệt rõ token của người và token của máy. Xem [API kiểm token](https://docs.dbiz.com/sso/api-backend.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.