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

# Kết nối web SPA với Keycloak bằng PKCE

> Cấu hình client public và mã mẫu oidc-client-ts để app chạy trên trình duyệt đăng nhập qua Keycloak bằng Authorization Code kèm PKCE S256.

App chạy hoàn toàn trên trình duyệt (React, Vue, Next.js xuất tĩnh) không giữ được bí mật, nên dùng client public với Authorization Code kèm PKCE S256. Trang này liệt kê cấu hình client cần yêu cầu và mã mẫu với `oidc-client-ts`.

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

| Thuộc tính | Giá trị |
| - | - |
| Client authentication | Off (client public, không có secret) |
| Standard flow | On |
| PKCE | `S256`, bắt buộc |
| Direct access, Implicit, Service account | Off |
| Valid redirect URIs | `https://<app-host>/<duong-callback>`. Càng cụ thể càng tốt, chỉ dùng `/*` khi router cần |
| Valid post logout redirect URIs | `https://<app-host>/` hoặc trang hiển thị sau khi đăng xuất |
| Web origins | `https://<app-host>`, không có `/` cuối |
| Audience mapper | Cần nếu backend của bạn kiểm `aud` |

## Mã mẫu với oidc-client-ts

```ts auth.ts theme={null}
import { UserManager, WebStorageStateStore } from "oidc-client-ts";

export const userManager = new UserManager({
  authority: "https://<id-host>/realms/<realm>",       // = iss
  client_id: "<client-id>",
  redirect_uri: `${window.location.origin}/callback`,
  post_logout_redirect_uri: `${window.location.origin}/`,
  response_type: "code",                                // PKCE S256 tự bật với code flow
  scope: "openid",
  automaticSilentRenew: true,                           // access token sống ngắn
  userStore: new WebStorageStateStore({ store: window.sessionStorage }),
});
```

```ts callback.ts theme={null}
// Trang /callback: đổi code lấy token
await userManager.signinRedirectCallback();
```

```ts logout.ts theme={null}
// Tự gắn id_token_hint và post_logout_redirect_uri
await userManager.signoutRedirect();
```

Gửi access token tới API trong header `Authorization: Bearer <access_token>`.

> [!WARNING]
>
> Với Next.js, biến `NEXT_PUBLIC_*` bị đóng cứng vào bundle lúc build. Đổi issuer hay client thì phải build lại, sửa biến môi trường thôi là chưa đủ. Xem [Lỗi thường gặp](https://docs.dbiz.com/sso/loi-thuong-gap.md).

## Tiếp theo

* [Đăng xuất](https://docs.dbiz.com/sso/dang-xuat.md): kết thúc luôn phiên Keycloak khi người dùng bấm Logout.
* [API kiểm token](https://docs.dbiz.com/sso/api-backend.md): backend nhận token từ SPA kiểm những gì.


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