Keycloak login for iOS and Android apps with AppAuth

Native apps should sign users in through the system browser with AppAuth, a public Keycloak client and PKCE. This page covers the configuration, token storage, logout and the failure points teams hit most.

On this page

How Keycloak login for mobile apps with AppAuth works

If your team is shipping an iOS or Android app that must sign users in through Keycloak, the supported method is the OpenID Connect authorization code flow with PKCE, run from the system browser through AppAuth against a public client. The app never holds a client secret. Instead, AppAuth starts the flow in the system browser, Keycloak authenticates the user on its own login pages, and the app receives an authorization code on a redirect URI it registered. The app then exchanges that code, along with a PKCE code verifier, for tokens. This page covers the client configuration in Keycloak, the redirect URI choices for custom schemes and app links, how refresh tokens are kept on the device, and how sign-out is handled.

This page does not cover backend-for-frontend patterns, where a server holds the tokens for a browser or app, and it does not cover how APIs validate the access tokens they receive. Single logout across other applications is also outside its scope. Those topics have their own sibling pages, and you should read them if your architecture routes mobile traffic through a server or if sessions must end in several apps at once. The guidance here follows the Keycloak server administration guide and the Keycloak documentation for the current release line, which is the basis for every client setting described. Confirm the exact client options in the admin console for the Keycloak version you run, because option names and defaults can change between minor releases.

What a Keycloak mobile login project needs before setup

A native app login project depends on four things being in place before anyone writes client code: a production Keycloak deployment, mobile toolchain owners, control of the domain that proves app ownership, and a clear picture of the identity sources and MFA rules already in the realm. Confirm each one early, because changes later move the redirect URIs, token policies and test plan.

Production Keycloak deployment

Mobile sign-in is only as stable as the server behind it. Plan a production database from the supported list rather than the default dev-file database, which the Keycloak database guide reserves for development. Confirm TLS on all communication, a reverse proxy with path restrictions, and the admin console and Administration REST API on a hostname separate from the public frontend URL that the apps will call. Ask who owns certificate renewal at the proxy.

Production guide

Production database choice

Pick the database engine and version from Keycloak's supported list before the realm is built, since the realm, clients and user store all live there. Confirm which PostgreSQL major version your environment runs, because the supported range is stated in the database guide. Also confirm who performs backups and restores of the database, since a lost realm means every app's client registrations and user accounts must be rebuilt.

Database guide

Mobile toolchain and AppAuth versions

Name the people who own the iOS and Android projects and the system browser behavior each platform provides. AppAuth is the library that runs the authorization code flow with PKCE through the system browser on each platform, so the iOS and Android teams must agree on one library approach per platform. Confirm the AppAuth release each team will pin, and check its current release notes with the library maintainers, since this page does not list library versions.

Keycloak server docs

Domain control for app links

Redirect URIs for mobile apps can use a custom scheme or an app link tied to a domain you control. An app link requires a file published on that domain that names your app, so whoever controls DNS and web hosting for the domain must be part of the project. Confirm who can publish files to the domain, how changes are approved, and whether the domain is shared with other teams, since shared control makes ownership of the redirect URI harder to prove.

Identity sources in the realm

List the user federation and identity brokering providers already connected to the realm, such as LDAP or Active Directory, Kerberos, or upstream OIDC and SAML providers. Each one changes how users log in on a phone, which attributes arrive in the token, and which login screens appear in the system browser. Confirm which sources are authoritative for each user population and who can change them, because mobile clients inherit those decisions.

MFA and passkey policies

Decide which second factors and authentication flows apply to mobile logins before the app is built. Check whether OTP policies, WebAuthn or passkeys with conditional and modal UI, and recovery codes are enabled in the realm, and whether any step-up rules depend on the client. Confirm how users on phones without an enrolled factor will recover access, because a mobile app cannot fall back to a desktop browser as easily as a web app can.

Configure the Keycloak client and the apps in sequence

This sequence sets up a dedicated Keycloak realm and a public client for the mobile apps, then wires AppAuth on iOS and Android to that client. Each step ends with a check so the team knows the login path works before moving on.

  1. Create the realm and test users

    An administrator creates a dedicated realm for the mobile apps so their clients, users and token settings stay separate from other applications. Create at least one test user with a known password in that realm, and record the realm's issuer URL, which has the form of your Keycloak base address followed by the realm path. Open that issuer URL's well-known OpenID configuration in a browser on the admin workstation. The check is that the response loads over TLS and lists the authorization and token endpoints.

  2. Create the public client with PKCE enforced

    In the realm, create an OpenID Connect client with client authentication turned off, because a mobile app cannot keep a client secret. Enable standard flow only, disable implicit and direct access grants, and require PKCE with the S256 code challenge method in the client's advanced settings. Confirm the exact client ID the apps will send, since AppAuth must match it character for character. The check is that the client's settings page shows public access with standard flow enabled and PKCE set to S256.

  3. Register the redirect URIs exactly as the apps use them

    Add the redirect URIs that each app passes to AppAuth as valid redirect URIs on the client. For a custom scheme, the entry is the scheme and path the app registers in its iOS or Android manifest. For app links or universal links, register the HTTPS URI the app handles and confirm that the domain serves the association file for the app. Keycloak compares URIs exactly, so a trailing slash or a different path causes a failed login. The check is that a browser test with the redirect URI reaches the app's callback handler rather than a Keycloak error page.

  4. Set web origins and post-logout redirect URIs

    Set the web origins field to the values the client needs, and keep it empty or minimal because native apps do not run in a browser origin. Add the post-logout redirect URI that the app uses after RP-initiated logout, and register it separately from the login redirect URIs. Ask your security team to confirm that no wildcard entries remain on the client, since broad redirect patterns widen the set of places an authorization code can be sent. The check is that the client settings list only the login and logout URIs you intended, with no wildcards.

  5. Wire AppAuth on iOS using the issuer discovery URL

    In the iOS project, configure AppAuth with the realm's issuer URL so the library reads the discovery document and finds the endpoints. Set the client ID, the redirect URI and the scopes, including openid and any profile or email scope the app needs. Start the login from the system browser session, which AppAuth provides by default, and complete the sign-in with the test user. The check is that the app receives tokens, the ID token decodes to a payload with the expected subject, email and name claims, and the token response includes a refresh token.

  6. Wire AppAuth on Android using the same client

    Configure AppAuth for Android with the same issuer URL, client ID, scopes and redirect URI scheme used on iOS, so both platforms share one client definition in Keycloak. Declare the redirect handling in the Android manifest and confirm the custom tab or browser launch behaves as expected on the test device. Run the same test user through the flow. The check is that the login completes, the returned ID token contains the same claims as the iOS test, and the app can read the user's name from the decoded token.

  7. Enable and verify refresh token behavior

    Confirm in the realm's token settings how long refresh tokens remain valid and whether they rotate on use, then match those settings to your policy for mobile sessions. In each app, store the refresh token in the platform's secure storage, such as the iOS Keychain or the Android Keystore-backed store, and never in plain preferences. Use AppAuth to exchange the refresh token for a new access token, then confirm the app still works after the access token expires. The check is that a refresh returns a new access token without showing the login screen, and that the stored token is absent from logs and backups.

  8. Test logout and the decoded claims end to end

    Run RP-initiated logout from each app and confirm the user is redirected to the registered post-logout URI and that the app discards its tokens. Then repeat the login with a second test user and compare the decoded ID token claims against the list your application team expects. Ask the identity team to confirm that the session no longer exists in the Keycloak admin console after logout. The check is that the logout returns to the registered URI, the stored refresh token is cleared, and the claims match the expected set for both users.

Custom scheme or app link: which redirect URI to register

The choice is between a custom URI scheme (for example, com.example.app:/oauth2redirect) and a verified app link, which is a universal link on iOS or an app link on Android tied to a domain you control. A custom scheme needs no domain setup, so it is quick to start with, but any app installed on the same device can register the same scheme. Another app could then receive the authorization code during sign-in. Verified app links are bound to a domain through a file you host on that domain (an apple-app-site-association file on iOS, a Digital Asset Links file on Android) and to the app's signing identity, so the operating system only routes the callback to your app. The cost is operational: you must control the domain, publish and keep those files current, configure associated domains or intent filters in each app build, and handle the redirect in both the app and your web fallback.

Whichever option you pick, PKCE protects the code exchange, which limits what an intercepted code is worth, but it does not remove the risk of a hijacked redirect. Many teams register a custom scheme for development and a verified app link for production, which means two redirect URIs in the same Keycloak client. Confirm the current requirements for universal links and app links with Apple and Google before you finalize the design, since platform rules for domain association, signing and fallback behavior change over time. Also confirm how your AppAuth release handles the callback on each platform.

In the Keycloak client, the redirect URI list is matched exactly. Scheme, host, path, and trailing slash must all agree with the value the app sends, and wildcards that cover arbitrary paths on a verified domain widen the set of callbacks Keycloak will accept. Keep the list to the callbacks each build actually uses, remove development entries before release, and set post-logout redirect URIs the same way. Test sign-in and sign-out on a clean device for every registered URI, because a mismatch usually appears only as an error page after the user authenticates.

How Keycloak claims map to mobile app profile and session data

This table shows which Keycloak token element feeds each part of the mobile app's profile and session state, and which client mapper settings must be on for the app to read it. Use it to decide what the app reads from the ID token, what it sends to APIs as the access token, and what it must never keep or show. Check each row against your own realm before release, because mapper names and claim availability depend on your client configuration.

Data itemSource in KeycloakHow the app should use itClient or mapper setting to confirm
Subject (sub)ID token, always issued for an OpenID Connect login with the openid scopeUse as the stable user key for the local profile and for matching cached data to the accountConfirm the client requests the openid scope; do not map a different attribute onto sub
Email and display nameID token claims email and name, emitted when the profile and email scopes are requestedShow in the profile screen; re-read on each login rather than treating the first value as permanentConfirm the default client scopes include profile and email, and that the user has the attributes filled in
Preferred usernameID token claim preferred_usernameDisplay only; do not use it as the unique key because users can change itConfirm the profile scope mapper emits it for this client
Access token audienceAccess token aud claim, set by an audience mapper for the API the app callsSend the access token only to the API it was issued for; the app itself should not treat it as a source of profile dataAdd an audience mapper that names the resource API client, and confirm the API validates aud
Roles and groupsRealm and client role mappers, or group membership mappers, added to the ID token or access tokenUse to show or hide features in the UI; the API must still enforce access on the serverConfirm the role or group mapper is set to add to the ID token if the app reads it, and to the access token if the API reads it
Refresh tokenIssued at login when the client is allowed to use refresh tokens; lifetime set in realm token settingsStore in the platform keystore (Keychain on iOS, Keystore on Android) and use it to renew access without a new browser loginConfirm refresh token issuance is enabled for the public client and check the refresh token lifetime and rotation settings
App session stateDerived from token expiry, the ID token and the local sign-in stateKeep a session flag that clears when refresh fails, the user signs out, or the device loses its keystore entryConfirm the token lifespans match the session length you intend, and test a refresh after the access token expires
Passwords, raw credentials and sensitive claimsNot issued by Keycloak to the app; claims can still contain personal data that the realm exposesNever store or display passwords, client secrets, or full token strings in logs, screenshots or analyticsRemove any custom claims the app does not need so the ID token carries only data the app uses

Securing refresh tokens and the device session

A public mobile client has no secret to protect, so the device session depends on where tokens live, how long refresh tokens last, and how quickly access can be cut off after a lost phone. The cards below cover the decisions that connect the app, the realm settings and the production baseline for Keycloak.

Store tokens in platform secure storage

Keep refresh tokens in the iOS Keychain and in Android storage backed by the Keystore, never in plain preferences or files. Set accessibility attributes so tokens are unavailable while the device is locked and do not migrate to other devices through backups. Access tokens are short-lived, so keep them in memory where the app design allows. Ask your mobile team to confirm the exact Keychain and Keystore settings in writing before the threat model review.

Keep tokens out of logs and backups

Token values appear in crash reports, debug logs, analytics events and HTTP traces when developers are careless. Redact authorization headers and token fields in every logging layer, and exclude token storage from cloud and device backups. Test a release build with a proxy and a log collector to confirm no bearer or refresh token is written anywhere outside secure storage.

Set refresh token lifetime and rotation in the realm

Refresh token lifetime, idle timeout and rotation are realm and client settings in Keycloak, so they belong in configuration review, not only in app code. Choose a maximum session length that matches the risk of the app, and turn on refresh token rotation so each use issues a new refresh token. Confirm the current option names and defaults in the server administration guide for your release before you set values.

Keycloak server admin docs

Revoke sessions after a lost device

A stolen phone keeps its refresh token until the session ends, so the support path must be planned before launch. Define how an administrator or user ends sessions for a device or account, for example by logging out a user's sessions in the admin console or through the Administration REST API. Test that a revoked refresh token fails at the token endpoint and that the app returns the user to sign-in.

Use the system browser, not embedded web views

AppAuth opens the login page in the system browser, which keeps credentials out of the app and lets the user's existing Keycloak session and passkeys work. Embedded web views let the app see typed passwords and cookies, so do not use them for sign-in. Verify in testing that the authorization request opens in the system browser on both platforms and that the redirect returns to the app through the registered redirect URI.

Rely on PKCE and exact redirect URIs

A public client has no client secret, so the security of the code exchange rests on PKCE and on exact redirect URI matching. Require PKCE with the S256 method for the client, register only the custom scheme or app link URIs the app uses, and avoid wildcards. Ask your Keycloak administrator to confirm these settings in the client definition and to review them after each change.

Enforce TLS and production hardening

Every call from the app to Keycloak must use TLS, and the public hostname should sit behind a reverse proxy that restricts paths, as the production guide describes. Keep the admin console and Administration REST API on a separate hostname or context path from the public frontend URLs the app calls. Certificate pinning and network controls are design decisions to agree with your security team, not defaults that Keycloak provides.

Production configuration guide

Logging users out on the device and at Keycloak

Logging out of a mobile app is two separate actions, and the app must do both. Clearing the tokens stored on the device only removes the app's copy of the session. Ending the Keycloak session asks the identity server to terminate the user's browser session in the realm, so the next sign-in cannot silently reuse it. AppAuth supports the second action through an end-session request, which opens the system browser at the Keycloak end-session endpoint with the id_token_hint for the user and a post_logout_redirect_uri that Keycloak returns the user to after the session ends. That redirect URI must be registered in the client's valid post logout redirect URIs, using the same custom scheme or app link pattern as the sign-in redirect. Ask your team to confirm the exact parameters against the AppAuth version you ship and the Keycloak OIDC documentation for your release.

The end-session request goes through the system browser for the same reason sign-in does: the browser holds the Keycloak cookie that identifies the session, and AppAuth cannot end that session from inside the app. If the user signed in on another device or in a web app, Keycloak ends only the session it can identify from this browser. Other sessions stay active until they expire or another mechanism ends them. Ending those sessions everywhere is a separate design problem covered in the single logout topic, which depends on how each application receives logout signals. Plan the user-facing behavior now: decide whether a failed or cancelled browser step still clears local tokens, and tell users what happens when they sign out on a phone but remain signed in on a laptop.

Some logouts never reach the device, for example when a phone is lost, the app is deleted, or the browser step is blocked. In those cases the only control left is time. Keep access token lifetimes short in the Keycloak realm, and make refresh token lifetimes and rotation match your risk tolerance, since a stolen refresh token is what keeps access alive after logout. Confirm with your security team how long a revoked or ended session can still call your APIs, and test that window on a real device before release.

Why mobile sign-in fails and how to fix each cause

This table lists the failures teams most often hit when wiring AppAuth to Keycloak, with the cause and the fix for each. Read it when a login loop, token error or logout problem appears, and check the Keycloak client settings before changing app code.

FailureCauseFix
Redirect URI mismatchThe redirect URI in the app does not exactly match a valid redirect URI on the Keycloak client, including scheme, path and trailing slash.Register the exact custom scheme or app link URI in the client's valid redirect URIs and match the app's configured redirect string character for character.
Missing PKCE or wrong client typeThe client is set as confidential or PKCE is not enforced, so the code exchange fails or a client secret is embedded in the app.Create the mobile client as a public client, enable PKCE with the S256 method, and never ship a client secret in the app binary.
App link files not verifiedThe domain's association file is missing, unreachable over HTTPS, or served with the wrong content type, so the OS opens the browser instead of the app.Publish the association files at the required well-known paths on the domain, confirm the app identifier and signing details, and test on a device that has reinstalled the app.
Web view blocking or breaking the flowAn embedded web view is used for sign-in, which identity providers and Google or Apple sign-in can block, and it does not share the system browser session.Use AppAuth with the system browser (custom tabs on Android, an authentication session on iOS) rather than an embedded web view for the Keycloak login page.
Refresh token invalidatedRefresh token rotation, realm session limits or idle timeouts end the session, so the next refresh returns an invalid grant error.Store the newest refresh token after each refresh, review the realm's session and refresh token settings, and send users to a fresh sign-in when refresh fails.
Clock skew on devicesA device clock that runs ahead or behind makes freshly issued tokens look expired or not yet valid during validation.Keep devices on network time, allow a small leeway in the token checks the app and APIs perform, and confirm that Keycloak and API clocks are synchronized.
Issuer URL points at the admin hostnameThe app's discovery URL uses the admin console hostname or context path, so the issuer in tokens does not match what the app expects.Set the frontend URL in Keycloak to the public hostname and use the public issuer for discovery, keeping the admin console on a separate hostname as the production guide describes.
Logout lands on an unregistered post-logout URIThe app sends a post-logout redirect URI that is not listed in the client's valid post-logout redirect URIs, so Keycloak refuses to redirect.Add the exact post-logout redirect URI to the client settings and confirm that the app sends the same value during end-session requests.

Questions teams ask before building Keycloak login into a mobile app

What drives the effort of a Keycloak login build for iOS and Android?

The effort follows the number of platforms, the identity sources behind the realm, and the sign-in policy you require. Two native apps need two AppAuth integrations, two sets of redirect configuration and two release tracks. Existing identity sources such as LDAP, Active Directory or an upstream identity provider add mapping and testing work. Custom branding of the login pages, MFA and passkey policy, and app link setup each add configuration and verification steps. Ask for the scope to list each of these items separately so you can see what is included and what is left for later.

Can our internal team build Keycloak login into the app without a partner?

Yes, if your team already has mobile engineers who know OAuth 2.0 and OpenID Connect and has someone who can administer the Keycloak realm. AppAuth is an open source library for native apps, and the work centers on a public client with PKCE, a redirect URI that the app can receive, secure token storage on the device, and a logout path. The harder parts are usually the realm and client settings on the server, app link verification and release coordination. Decide early whether your team will own those server-side pieces or hand them to a partner for a fixed scope.

What do we need to provide before an implementation starts?

Plan to provide administrative access to the Keycloak realm or a change process that lets the implementer create and test clients, plus access to the app store accounts that release your builds. A test realm with test users is strongly preferable to working in production, so that redirect URIs, scopes and token lifetimes can be checked without affecting real users. You will also need the bundle identifiers, package names, signing details and the domain you plan to use for app links, along with the people who can approve changes to DNS or the website association file.

How long does a mobile Keycloak login project usually take?

The duration depends on scope rather than on a fixed formula. A single platform with an existing realm and a standard sign-in policy is a much smaller piece of work than two platforms with custom branding, federated directories and passkey requirements. Store review cycles, app link verification and any security review your organization runs can add calendar time that the build itself does not. Ask for a timeline in the written scope that separates build work, test cycles, store submission and any waiting on your own approvals.

Does the Keycloak license or a Red Hat subscription change the mobile work?

The license does not change the mobile integration itself. Keycloak is licensed under Apache 2.0, and the AppAuth client configuration, PKCE flow and redirect handling are the same whichever distribution you run. A Red Hat build of Keycloak subscription changes who supplies support, patches and lifecycle commitments for the server, not how the app authenticates. Confirm the distribution, version and support terms with your vendor or procurement team, since those decisions affect the upgrade plan and your support contacts rather than the app code.

What ongoing upgrade work do Keycloak and AppAuth need after launch?

Both components need planned maintenance. Keycloak publishes releases on a regular cadence and documents upgrade notes for each one, so your team should review those notes, test the realm and client configuration on a staging server, and then roll out the change. AppAuth updates should be tested on current iOS and Android releases before you ship a new app version. Each upgrade should include regression tests for sign-in, token refresh and logout on both platforms. Ask whether the scope includes these upgrades or whether they will be handled under a separate support arrangement.

What breaks most often in a native app login flow?

The most common failures involve redirect URIs that do not exactly match the registered value, app link or custom scheme configuration that is not verified on the device, and refresh tokens that are stored in places the operating system can read more easily than intended. Logout also needs attention, because ending the session in the system browser does not automatically clear tokens held by the app. Build a test matrix that covers first sign-in, token refresh after expiry, sign-out, reinstall and sign-in on a second device before you release.

Which checks should we ask for before the app goes to production?

Ask for evidence that the Keycloak client is a public client with PKCE enabled, that redirect URIs are limited to the exact values the apps use, that app link files are served over TLS on the expected domain, and that refresh tokens are stored in the platform secure storage facilities. Also ask for a documented logout test and a record of how the realm enforces MFA or passkey policy for mobile sign-in. These checks give your security and compliance teams records they can review, though they do not replace an independent audit or certification.

How the AppAuth login flow moves between the app, the browser and Keycloak

The flow starts when the mobile app calls AppAuth, which opens the system browser at the Keycloak authorization endpoint with a PKCE code challenge. The user signs in on Keycloak, and the browser returns an authorization code to the app through the redirect URI. The app then sends the code and the original code_verifier to the token endpoint, where Keycloak checks them before issuing tokens. Check that the code exchange happens without a client secret, and that tokens end up only in device storage that your app controls.

Authorization code flow with PKCE, from the app through the system browser to Keycloak and back.

How DeployOpen scopes and delivers a mobile Keycloak login

DeployOpen usually agrees a fixed scope in writing before any mobile work starts. For an AppAuth login, that scope names the Keycloak client for each app (a public client with PKCE, with no client secret in the binary), the exact redirect URIs for the iOS and Android builds, the app integration on each platform, the token storage and refresh behavior, the logout path, and the test plan. Each item becomes a deliverable with an owner and an acceptance check, so the quote follows from what is written down rather than from a general estimate. Timelines and prices are set against that document, not against a template.

The Keycloak side of the work runs in the client's own infrastructure. DeployOpen deploys and hardens the Keycloak instance there, configures the realm and the mobile clients, and documents the settings the security and compliance teams will review. Security testing covers the mobile login itself: redirect handling, PKCE enforcement, token exposure on the device, and whether logout actually ends the session. Testing on real iOS and Android devices is part of the agreed scope, because emulators do not reproduce how each platform handles the system browser, app links and secure storage. Ask the partner to name which device and OS versions the test plan covers.

After go-live, upgrades and ongoing support are available as a retainer. Keycloak ships minor releases several times a year, so a retainer should state who tests a Keycloak upgrade against the mobile clients, who updates the AppAuth configuration if a redirect URI or client setting changes, and how a security finding is triaged. Confirm these terms in the written scope before signing, including what is one-time work and what recurs.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.