> ## 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 app mobile iOS, Android, Flutter với Keycloak

> Cấu hình client public cho app iOS, Android, Flutter, cách custom scheme đưa kết quả đăng nhập về app, kèm mẫu AppAuth và flutter_appauth.

App mobile phát hành tới máy người dùng nên không giữ được bí mật: dùng client public với Authorization Code kèm PKCE S256, đăng nhập qua trình duyệt hệ thống và nhận kết quả qua custom scheme hoặc universal link. Trang này giải thích luồng đó và có mẫu cho Android, iOS và Flutter.

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

| Thuộc tính | Giá trị |
| - | - |
| Client authentication | Off (client public). Không nhúng secret vào app: secret nằm trong IPA/APK coi như đã lộ |
| Standard flow | On, PKCE `S256` |
| Direct access | Off. Không tự làm màn đăng nhập rồi gửi mật khẩu |
| Valid redirect URIs | Custom scheme dạng reverse-domain, ví dụ `com.dbiz.<app>:/oauth2redirect`; hoặc universal link / App Link `https://<app-host>/oauth2redirect` |
| Valid post logout redirect URIs | `com.dbiz.<app>:/logout` hoặc link tương ứng |
| Web origins | Để trống |
| `offline_access` | Chỉ xin khi thật sự cần phiên dài |

Mỗi nền tảng dùng một client riêng. Không dùng chung client của bản web.

## App biết gọi Keycloak ở đâu?

Custom scheme chỉ dùng cho chiều Keycloak trả kết quả về app. Chiều app gọi Keycloak luôn đi bằng `https` tới issuer khai trong code. Từ issuer, thư viện tự tải discovery để lấy địa chỉ trang đăng nhập, token endpoint và logout endpoint.

**1. App đọc discovery**

App gọi `https://<id-host>/realms/<realm>/.well-known/openid-configuration` để lấy `authorization_endpoint`, `token_endpoint`, `end_session_endpoint`.

**2. App mở trình duyệt hệ thống**

Trình duyệt mở trang đăng nhập với `client_id`, `redirect_uri=com.dbiz.<app>:/oauth2redirect`, `code_challenge` và `state`. `redirect_uri` chỉ là địa chỉ trả về.

**3. Người dùng đăng nhập**

Người dùng nhập tài khoản trên trang của Keycloak, không phải trong app.

**4. Hệ điều hành chuyển kết quả cho app**

Keycloak chuyển trình duyệt tới `com.dbiz.<app>:/oauth2redirect?code=...&state=...`. Hệ điều hành thấy scheme đã được app đăng ký nên mở app và đưa URL cho app.

**5. App đổi code lấy token**

App gọi token endpoint bằng `https`, gửi `code` và `code_verifier`, nhận access token, id token và refresh token.

Khai scheme trong `Info.plist` (iOS) hay `AndroidManifest` / `build.gradle` (Android) không trỏ tới server nào. Nó chỉ báo hệ điều hành rằng URL bắt đầu bằng scheme đó thì mở app này. Keycloak không gọi thẳng vào app; nó chỉ chuyển hướng trình duyệt.

Universal link (iOS) và App Link (Android) an toàn hơn custom scheme vì app khác không chiếm được. Đổi lại, cần một host công khai phục vụ `/.well-known/apple-app-site-association` và `/.well-known/assetlinks.json`.

> [!WARNING]
>
> Dùng trình duyệt hệ thống (ASWebAuthenticationSession trên iOS, Custom Tabs trên Android). Không dùng WebView nhúng để đăng nhập.

## Mã mẫu

> [tab] Flutter
>
> Khai scheme redirect cho từng nền tảng (viết thường, dạng reverse-domain):
>
> ```kotlin android/app/build.gradle.kts theme={null}
> android {
>     defaultConfig {
>         manifestPlaceholders["appAuthRedirectScheme"] = "com.dbiz.<app>"
>     }
> }
> ```
>
> ```xml ios/Runner/Info.plist theme={null}
> <key>CFBundleURLTypes</key>
> <array>
>   <dict>
>     <key>CFBundleURLSchemes</key>
>     <array><string>com.dbiz.<app></string></array>
>   </dict>
> </array>
> ```
>
> ```dart lib/auth.dart theme={null}
> // pubspec.yaml: flutter_appauth, flutter_secure_storage
> import 'package:flutter_appauth/flutter_appauth.dart';
> import 'package:flutter_secure_storage/flutter_secure_storage.dart';
>
> const issuer = 'https://<id-host>/realms/<realm>';
> const clientId = '<mobile-client-id>';
> const redirectUrl = 'com.dbiz.<app>:/oauth2redirect';
> const postLogoutUrl = 'com.dbiz.<app>:/logout';
>
> final appAuth = const FlutterAppAuth();
> final storage = const FlutterSecureStorage();
>
> // Đăng nhập: Authorization Code + PKCE S256 (thư viện tự sinh code_verifier)
> Future<void> login() async {
>   final res = await appAuth.authorizeAndExchangeCode(
>     AuthorizationTokenRequest(
>       clientId,
>       redirectUrl,
>       issuer: issuer,             // tự đọc discovery
>       scopes: ['openid'],         // thêm 'offline_access' chỉ khi cần phiên dài
>     ),
>   );
>   await storage.write(key: 'refresh_token', value: res.refreshToken);
>   await storage.write(key: 'id_token', value: res.idToken);
>   // res.accessToken sống ngắn: giữ trong bộ nhớ, gửi kèm header Authorization
> }
>
> // Làm mới access token
> Future<String?> refresh() async {
>   final rt = await storage.read(key: 'refresh_token');
>   if (rt == null) return null;
>   final res = await appAuth.token(
>     TokenRequest(clientId, redirectUrl, issuer: issuer, refreshToken: rt, scopes: ['openid']),
>   );
>   await storage.write(key: 'refresh_token', value: res.refreshToken);
>   return res.accessToken;
> }
>
> // Đăng xuất: kết thúc phiên Keycloak rồi xoá token trên máy
> Future<void> logout() async {
>   await appAuth.endSession(
>     EndSessionRequest(
>       idTokenHint: await storage.read(key: 'id_token'),
>       postLogoutRedirectUrl: postLogoutUrl,
>       issuer: issuer,
>     ),
>   );
>   await storage.deleteAll();
> }
> ```
>
> Nếu không muốn thư viện tự đọc discovery, truyền `serviceConfiguration` thay cho `issuer`:
>
> ```dart lib/auth_static.dart theme={null}
> AuthorizationTokenRequest(
>   clientId, redirectUrl,
>   serviceConfiguration: const AuthorizationServiceConfiguration(
>     authorizationEndpoint: 'https://<id-host>/realms/<realm>/protocol/openid-connect/auth',
>     tokenEndpoint: 'https://<id-host>/realms/<realm>/protocol/openid-connect/token',
>     endSessionEndpoint: 'https://<id-host>/realms/<realm>/protocol/openid-connect/logout',
>   ),
>   scopes: ['openid'],
> )
> ```

> [tab] Android (AppAuth)
>
> ```kotlin LoginActivity.kt theme={null}
> AuthorizationServiceConfiguration.fetchFromIssuer(
>     Uri.parse("https://<id-host>/realms/<realm>")) { cfg, ex ->
>     val req = AuthorizationRequest.Builder(
>             cfg!!, "<mobile-client-id>", ResponseTypeValues.CODE,
>             Uri.parse("com.dbiz.<app>:/oauth2redirect"))
>         .setScopes("openid")                  // AppAuth tự sinh PKCE S256
>         .build()
>     // mở bằng AuthorizationService.getAuthorizationRequestIntent(req)
> }
> ```

> [tab] iOS (AppAuth)
>
> ```swift LoginViewController.swift theme={null}
> let issuer = URL(string: "https://<id-host>/realms/<realm>")!
> OIDAuthorizationService.discoverConfiguration(forIssuer: issuer) { cfg, _ in
>   let req = OIDAuthorizationRequest(configuration: cfg!, clientId: "<mobile-client-id>",
>       scopes: [OIDScopeOpenID], redirectURL: URL(string: "com.dbiz.<app>:/oauth2redirect")!,
>       responseType: OIDResponseTypeCode, additionalParameters: nil)
>   // trình bày bằng OIDAuthState.authState(byPresenting:presenting:callback:)
> }
> ```

React Native dùng `react-native-app-auth` với các giá trị tương tự.

## Lưu token an toàn

* Lưu refresh token trong Keychain (iOS) hoặc Keystore / EncryptedSharedPreferences (Android). Flutter dùng `flutter_secure_storage`.
* Giữ access token trong bộ nhớ.
* Refresh token báo `invalid_grant` thì xoá token và cho người dùng đăng nhập lại.


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