Skip to content

About

Native mobile SDKs for Keycloak auth (without the browser). Implementation of IETF draft OAuth 2.0 for First-Party Applications

Resources

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Native login for Keycloak

CI Keycloak 26.4 to 26.8 iOS 17+ Android 9+ React Native 0.84+ Flutter 3.35+ Web: React and web components License

Sign users in to Keycloak with your app's own screens. Keycloak keeps running the login flow, with its passwords, passkeys, one-time codes, push approvals, required actions and brute-force protection. These extensions hand each step to your app as JSON, and the SDKs for iOS, Android, React Native, Flutter and the web turn it into your app's own screens.

Native login for Keycloak: your app's screens, Keycloak's login flow

✨ Why

  • No browser sheet, no redirect. Browser-based login (AppAuth) shows a "wants to use … to sign in" prompt and Keycloak's web pages, and a single-page app redirects away to Keycloak. Here every step is a screen in your app.
  • The flow lives in Keycloak. Change the flow, add a second factor or require an action in the admin console, and every app follows without a release.
  • Unlike the password grant, it supports MFA, passkeys, required actions and brute-force rules, and tokens can be bound to the device with DPoP.

Some things stay on Keycloak's own pages: TOTP enrollment, social and enterprise identity providers, and registration and password reset in React Native and Flutter for now. When a login reaches one of those, the SDK finishes it in the system browser (a popup on the web) and the user comes back signed in.

🧭 How it works

sequenceDiagram
    participant App as Your app (SDK)
    participant KC as Keycloak + extensions
    App->>KC: start login
    KC-->>App: challenge: username β†’ shown as a native screen
    App->>KC: answer, then the next challenge… (one per step of your flow)
    KC-->>App: authorization code
    App->>KC: token request with PKCE and DPoP
    KC-->>App: tokens bound to the device key
Loading

The protocol follows the IETF draft OAuth 2.0 for First-Party Applications. Details: protocol and flows.

🧩 What runs natively

πŸ”‘ Passwords with the platform password manager: AutoFill on iOS, Credential Manager on Android
πŸͺͺ Passkeys sign in, enroll after a password login, or register one later in the app
πŸ”’ One-time codes TOTP, email and SMS codes, recovery codes
πŸ” PIN codes a short numeric PIN as a second factor, with the optional PIN extension
πŸ“² Push approval number matching, through APNs or Firebase Cloud Messaging
⬆️ Step-up ask for a stronger factor before a sensitive action
πŸ“‹ Required actions update password, verify email, accept terms, set a PIN, register a passkey or push device
πŸ†• Sign-up and forgot password registration from the realm's user profile, and a password reset with an emailed code (web, iOS and Android)
βš™οΈ Actions from your app "Change password", "Change PIN", "Verify email" or "Add a passkey" buttons in your settings: the user proves who they are first, can sign out other devices, and your app learns the outcome (Keycloak's kc_action)

| πŸ‘€ Account self-service | on the web, ready-made profile, sign-in methods, devices and organization switcher widgets |

Every SDK has default screens for all of these. Use them as they are, or replace them one at a time.

πŸš€ Try it locally

You need Docker, Java 21 and Maven, plus the toolchain for the platform you pick (Xcode, Android Studio, Node with pnpm, or Flutter). Start Keycloak with the demo realm:

git clone https://github.com/p2-inc/native-apps && cd native-apps/keycloak-native-auth
mvn -DskipTests -DskipITs package
cd demo && docker compose up --wait    # Keycloak on :8080, mailpit on :8025

The iOS demo app expects Keycloak on port 8089, so for iOS start it with KC_PORT=8089 docker compose up --wait instead.

Then run a demo app from the repository root and sign in as alice / alice-password. For the second factor, ./scripts/walkthrough.sh in the demo directory prints the current TOTP code (it needs curl, jq and openssl), or set up any authenticator app with the key alice-totp-secret-20261014.

From the repository root
πŸ“± iOS Open ios/KeycloakNativeDemo/KeycloakNativeDemo.xcodeproj and run it on a simulator (details)
πŸ€– Android cd android && ./gradlew :demo:installDebug with an emulator running (details)
βš›οΈ React Native cd react-native/keycloak-native-react-native && pnpm install && pnpm example ios (or android)
🐦 Flutter cd flutter/keycloak_native_flutter/example && flutter run
🌐 Web cd web && pnpm install && pnpm --filter keycloak-web-demo dev, then open http://localhost:5173 (React) or http://localhost:5173/elements.html (web components)

Every demo app has a Server screen to point it at another Keycloak: the server URL, realm and client IDs, saved on the device, with "Reset to defaults". Anything other than a local development host must use https. See Server settings.

Other demo users show other parts of the flow: bob gets an email code (read it in mailpit), hank has to accept terms, and carol has to update her password. All of them.

πŸ› οΈ Add it to your Keycloak

Keycloak 26.4 or later.

  1. Download keycloak-native-auth-providers-<version>.zip from the latest release and put all its jars in Keycloak's providers/ directory; they depend on each other. The zip also carries the optional factors' extensions (push MFA, and keycloak-pin for PIN codes); they do nothing until a flow uses them.
  2. Create an authentication flow named native from the native steps (native-username, native-password, native-totp, native-passkey and so on). Don't bind it as the browser flow: the native endpoint finds it by name, and a client or realm can choose another with the native-auth.flow-alias attribute. The demo realm is a working example to import or copy from.
  3. Create a public OpenID Connect client with PKCE S256 and the attribute native-auth.enabled set to true, and register a redirect URI such as myapp://auth/callback for logins that finish in the browser.

The server guide covers every setting, passkey domains and push. On Phase Two hosted Keycloak, contact us and we'll install the extensions on your cluster.

πŸ“± iOS

A Swift package for iOS 17+. In Xcode, add https://github.com/p2-inc/native-apps and link KeycloakNativeCore and KeycloakNativeUI.

import KeycloakNativeCore
import KeycloakNativeUI

let kc = KeycloakNative.configure(
  issuer: URL(string: "https://idp.example.com/realms/demo")!,
  clientId: "my-app"
)
let flow = kc.authentication().startLogin(LoginParameters(scope: "openid profile"))

// In a SwiftUI view:
NativeLoginView(kc: kc, flow: flow) { result in
  if case .authorized(let credentials) = result {
    Task { try await kc.credentialsManager().store(credentials) }
  }
}

πŸ“– iOS guide, including passkeys (Associated Domains) and push.

πŸ€– Android

Kotlin and Jetpack Compose for Android 9+ (API 28), from Maven Central.

implementation("io.phasetwo.keycloak.nativeauth:keycloak-native-android:0.3.0")
implementation("io.phasetwo.keycloak.nativeauth:keycloak-native-ui:0.3.0")
val kc = KeycloakNative.configure(
  URI("https://idp.example.com/realms/demo"),
  "my-app",
  KeycloakNative.Options(
    hardwareKeys = KeystoreDPoPKeys(context),                        // DPoP key in the Android Keystore
    secureStore = KeystoreSecureStore(context, namespace = "my-app"), // tokens sealed by the Keystore
  ),
)
val flow = kc.authentication().startLogin(LoginParameters(scope = "openid profile"))

// In a composable:
NativeLoginScreen(kc, flow, onResult = { result ->
  if (result is NativeLoginResult.Authorized) scope.launch { kc.credentialsManager().store(result.credentials) }
})

πŸ“– Android guide, including the activity setup for passkeys, saved passwords and the browser fallback.

βš›οΈ React Native

A TurboModule for React Native 0.84+ (New Architecture), with an Expo config plugin.

npm install @p2-inc/keycloak-native-react-native
import { KeycloakNative, NativeLoginScreen } from '@p2-inc/keycloak-native-react-native';

const kc = KeycloakNative.configure({ issuer: 'https://idp.example.com/realms/demo', clientId: 'my-app' });
const flow = await kc.authentication.startLogin({ scope: 'openid profile' });

<NativeLoginScreen
  kc={kc}
  flow={flow}
  onResult={async (result) => {
    if (result.kind === 'authorized') await kc.credentialsManager.store(result.credentials);
  }}
/>

πŸ“– React Native guide, including the Android activity and Expo setup.

🌐 Web

For single-page apps: the same challenge protocol in the browser, with DPoP, passkeys with autofill, step-up for your API calls and account self-service. No redirect to Keycloak unless a step has no native variant; then a popup carries it. Pick the layer that fits your stack:

Package For
@p2-inc/keycloak-web-react React: hooks and unstyled components (<SignIn>, <SignUp>, <StepUp>, <Profile>, <Credentials>, <Sessions>…) to style with your own CSS
@p2-inc/keycloak-elements Any framework or none (Vue, Angular, Svelte, server-rendered pages): web components with a styled default you theme with CSS variables, also as a single script-tag bundle
shadcn/ui registry React apps on shadcn/ui: npx shadcn add copies styled sign-in and account components into your code (details)
@p2-inc/keycloak-web The framework-free core, with LoginController to build your own UI in any framework
npm install @p2-inc/keycloak-web @p2-inc/keycloak-web-react
import { KeycloakWeb } from '@p2-inc/keycloak-web';
import { KeycloakProvider, SignIn } from '@p2-inc/keycloak-web-react';

const kc = KeycloakWeb.configure({ issuer: 'https://idp.example.com/realms/demo', clientId: 'my-spa' });

<KeycloakProvider kc={kc}>
  <SignIn onResult={(result) => console.log(result.kind)} />
</KeycloakProvider>

Or, without React:

<kc-sign-in heading="Sign in to Acme"></kc-sign-in>
<script type="module">
  import { configure } from '@p2-inc/keycloak-elements';
  configure({ issuer: 'https://idp.example.com/realms/demo', clientId: 'my-spa' });
</script>

πŸ“– Web guide: client settings (Web Origins, passkey origins), styling and replacing screens, the account widgets, web components, step-up with kc.fetch, tokens and sessions.

🐦 Flutter

A plugin for Flutter 3.35+ on iOS and Android.

flutter pub add keycloak_native_flutter
import 'package:keycloak_native_flutter/keycloak_native_flutter.dart';

final kc = await KeycloakNative.configure(
  issuer: Uri.parse('https://idp.example.com/realms/demo'),
  clientId: 'my-app',
);
final flow = await kc.authentication.startLogin(const LoginParameters(scope: 'openid profile'));

NativeLoginView(
  kc: kc,
  flow: flow,
  onResult: (result) async {
    if (result is NativeLoginAuthorized) await kc.credentialsManager.store(result.credentials);
  },
);

πŸ“– Flutter guide, including the Android activity setup.

πŸ” Security

  • PKCE on every login. DPoP binds the code, access token and refresh token to a key in the Secure Enclave or Android Keystore. We recommend DPoP for every app; your APIs then need to accept Authorization: DPoP and check the proof (details).
  • Tokens are stored in the Keychain or Keystore. In React Native and Flutter, the refresh token never reaches JavaScript or Dart.
  • On the web, the DPoP key is a non-extractable WebCrypto key: script on the page can use it but not copy it, so a stolen refresh token is useless elsewhere. Access tokens stay in memory (details).
  • Keycloak enforces the flow, MFA, brute-force rules and required actions, not the app.

Read the security model. To report a vulnerability, see SECURITY.md.

πŸ“Š Status

Pre-1.0: any release can change the protocol or the API, so pin exact versions. The Maven Central, npm and pub.dev packages above start with 0.3.0; the web packages are not on npm yet and first ship with 0.5.0.

The Keycloak extensions are integration-tested against Keycloak 26.4, 26.6 and 26.8. Each SDK is tested in CI by replaying recorded server exchanges, and the demo apps run on simulators, emulators and in the browser. Passkeys and push delivery on real devices are being verified now. See the roadmap.

πŸ“š Learn more

πŸ“„ License

The SDKs (iOS, Android and web), the React Native and Flutter wrappers, the web components, the shadcn registry and the demo setup are Apache 2.0. The Keycloak extensions are under the Elastic License 2.0, like Phase Two's other extensions: free to use and self-host, but not to offer as a hosted service.

Which license covers which files
Path License
Package.swift, ios/, android/, flutter/, react-native/, web/ (the packages, the shadcn registry and the demo app), spec/, docs/ Apache-2.0 (LICENSE, NOTICE)
keycloak-native-auth/demo/ except src/: compose files, realm export, resource server, scripts and recorded transcripts Apache-2.0 (LICENSE)
keycloak-native-auth/push-mfa-extension-java21/: ba-itsys' push MFA extension, rebuilt for Java 21 Apache-2.0 (LICENSE, NOTICE)
Everything else in keycloak-native-auth/, including the integration tests in demo/src/ ELv2 (COPYING)
keycloak-pin.jar in the providers zip: Phase Two's PIN extension, built from p2-inc/keycloak-pin ELv2 (COPYING)

Copyright 2026 Phase Two, Inc.

About

Native mobile SDKs for Keycloak auth (without the browser). Implementation of IETF draft OAuth 2.0 for First-Party Applications

Resources

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages