From 77b4ec02aeb0be4b33f9de4e2dbf12773859368c Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Tue, 17 Nov 2026 15:43:49 +0530 Subject: [PATCH 1/7] feat(skills): add agent skills for the Android SDK --- CLAUDE.md | 4 + skills/SKILL.md | 295 ++++++++++++++++++++++++++ skills/custom-token-exchange/SKILL.md | 62 ++++++ skills/mfa/SKILL.md | 118 +++++++++++ skills/organizations/SKILL.md | 67 ++++++ skills/passkeys/SKILL.md | 110 ++++++++++ 6 files changed, 656 insertions(+) create mode 100644 skills/SKILL.md create mode 100644 skills/custom-token-exchange/SKILL.md create mode 100644 skills/mfa/SKILL.md create mode 100644 skills/organizations/SKILL.md create mode 100644 skills/passkeys/SKILL.md diff --git a/CLAUDE.md b/CLAUDE.md index 728be37d3..e1dcd1ef1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,3 +135,7 @@ A PR touching public API, config, or integration patterns is not complete until | `EXAMPLES.md` + `examples/` | `EXAMPLES.md` is an index; each feature has its own file under `examples/` with full Kotlin + Java usage | See [references/docs-update.md](references/docs-update.md) for the full code-to-docs mapping. Read before finalizing any public API PR. + +## Agent Skills + +For task-specific integration guidance (setup, login, credentials, MFA, passkeys, organizations, custom token exchange), read [`skills/SKILL.md`](skills/SKILL.md) and its sub-skills. They are not packaged in the AAR; consumers read them from the GitHub repo (`auth0/Auth0.Android`, `skills/`). Keep them in sync with `README.md` and `examples/` when public API changes. diff --git a/skills/SKILL.md b/skills/SKILL.md new file mode 100644 index 000000000..f2e568f5f --- /dev/null +++ b/skills/SKILL.md @@ -0,0 +1,295 @@ +--- +name: auth0-android +description: >- + Use when adding Auth0 authentication to a native Android app (Kotlin or Java) + with the com.auth0.android:auth0 SDK: Gradle install, manifest placeholders and + callback URLs, WebAuthProvider login and logout, storing and refreshing tokens + with SecureCredentialsManager (including biometric protection), database + login, signup, passwordless, password reset, Custom Tabs, error handling, and + unit testing. Entry point for all Auth0.Android skills; use it even if the user + only says "add login to my Android app". +metadata: + type: core + library: Auth0.Android + library_version: 4.3.1 +--- + +# Auth0.Android + +Native Android authentication with `com.auth0.android:auth0` (v4, `minSdk` 26, Java 17). + +These skills are not packaged in the AAR. Read them from the GitHub repo: `skills/` in [auth0/Auth0.Android](https://github.com/auth0/Auth0.Android/tree/main/skills). Deeper docs live in the same repo: [`EXAMPLES.md`](https://github.com/auth0/Auth0.Android/blob/main/EXAMPLES.md) indexes `examples/*.md` (one file per feature, Kotlin and Java). Raw URLs work too: `https://raw.githubusercontent.com/auth0/Auth0.Android/main/examples/.md`. + +## Sub-skills + +| Task | Sub-skill | +|------|-----------| +| `mfa_required` handling, enroll, challenge, verify with `MfaApiClient` | [mfa/SKILL.md](./mfa/SKILL.md) | +| Passkey sign-in, signup, and enrollment with Credential Manager | [passkeys/SKILL.md](./passkeys/SKILL.md) | +| Organization login, invitations, reading `org_id` | [organizations/SKILL.md](./organizations/SKILL.md) | +| Exchange an external token for Auth0 tokens | [custom-token-exchange/SKILL.md](./custom-token-exchange/SKILL.md) | + +For DPoP, My Account API, Native to Web SSO, PAR, Auth Tab and other features, see the matching file under `examples/` (linked from `EXAMPLES.md`). + +## Prerequisites + +- Android `minSdk` 26+ and Java 17 (apps below API 26 must stay on the v3 line) +- An Auth0 application of type **Native** + +## Quick Start + +### 1. Install + +```groovy +// app/build.gradle +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = '17' } +} + +dependencies { + implementation 'com.auth0.android:auth0:4.3.1' +} +``` + +Check [Releases](https://github.com/auth0/Auth0.Android/releases) for the latest version. + +### 2. Configure the manifest + +```xml + +``` + +```groovy +// app/build.gradle, inside android { defaultConfig { ... } } +manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "https"] +``` + +`auth0Domain` and `auth0Scheme` are required: the library uses them to register the redirect intent-filter. `auth0Scheme` is `https` (Android App Links) or a lowercase custom scheme. + +In the Auth0 Dashboard, add this URL to both **Allowed Callback URLs** and **Allowed Logout URLs**: + +``` +https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback +``` + +`{YOUR_APP_PACKAGE_NAME}` is the `applicationId`. With a custom scheme, replace `https` with it. + +### 3. Create the Auth0 instance + +```xml + +YOUR_CLIENT_ID +YOUR_DOMAIN +``` + +```kotlin +val account = Auth0.getInstance(context) +// or: Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN") +``` + +`getInstance(context)` throws `IllegalArgumentException` if either string resource is missing. + +### 4. Log in and log out + +```kotlin +WebAuthProvider.login(account) + .withScope("openid profile email offline_access") + .start(this, object : Callback { + override fun onSuccess(result: Credentials) { + credentialsManager.saveCredentials(result) + } + + override fun onFailure(error: AuthenticationException) { + when { + error.isAuthenticationCanceled -> { /* user closed the browser */ } + error.isBrowserAppNotAvailable -> { /* no browser installed */ } + else -> { /* inspect error.getCode() / error.getDescription() */ } + } + } + }) + +WebAuthProvider.logout(account) + .start(this, object : Callback { + override fun onSuccess(result: Void?) { + credentialsManager.clearCredentials() + } + + override fun onFailure(error: AuthenticationException) { } + }) +``` + +Coroutines: `WebAuthProvider.login(account).await(context)` returns `Credentials` and `WebAuthProvider.logout(account).await(context)` returns `Unit`; both throw `AuthenticationException`. + +Builder options on `login`: `withScope`, `withAudience`, `withConnection`, `withConnectionScope`, `withOrganization`, `withInvitationUrl`, `withParameters` (for example `mapOf("prompt" to "login")`), `withScheme`, `withRedirectUri`, `withCustomTabsOptions`, `withEphemeralBrowsing`, `withTrustedWebActivity`, `withAuthTab`, `withMaxAge`, `withNonce`, `withState`. The default scope is `openid profile email`; `openid` is always enforced. Details: [`examples/web-auth-configuration.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/web-auth-configuration.md). + +Use a custom scheme only if you did not set `auth0Scheme` to `https`: set the placeholder, add the callback URL in the Dashboard, and call `.withScheme("myapp")` on both `login` and `logout`. + +### 5. Store and use credentials + +```kotlin +val apiClient = AuthenticationAPIClient(account) +val storage = SharedPreferencesStorage(context) +val credentialsManager = SecureCredentialsManager(apiClient, context, storage) + +credentialsManager.saveCredentials(credentials) + +if (credentialsManager.hasValidCredentials()) { + credentialsManager.getCredentials(object : Callback { + override fun onSuccess(result: Credentials) { + val accessToken = result.accessToken // refreshed automatically if expired + } + + override fun onFailure(error: CredentialsManagerException) { + when (error) { + CredentialsManagerException.NO_CREDENTIALS, + CredentialsManagerException.NO_REFRESH_TOKEN, + CredentialsManagerException.RENEW_FAILED -> { /* send the user to login */ } + else -> { /* see examples/credentials-manager.md */ } + } + } + }) +} +``` + +Coroutines: `credentialsManager.awaitCredentials()` throws `CredentialsManagerException`. Refresh needs a refresh token, so request `offline_access`. `CredentialsManager(apiClient, storage)` stores without encryption; prefer `SecureCredentialsManager`. In v4, `clearCredentials()` calls `Storage.removeAll()`, so it wipes everything in that storage, API credentials included; use a dedicated storage name if you share it. Full reference: [`examples/credentials-manager.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/credentials-manager.md). + +`CredentialsManagerException` has no string `code`. Compare against its companion constants (`NO_CREDENTIALS`, `NO_REFRESH_TOKEN`, `RENEW_FAILED`, `STORE_FAILED`, `DPOP_KEY_MISSING`, `SESSION_EXPIRED`, the `BIOMETRIC_*` family, and so on). `isDeviceIncompatible` is true on devices missing required crypto algorithms. + +### 6. Call an API + +Request the API audience at login with `.withAudience("https://api.example.com")`, then attach `credentials.accessToken` as `Authorization: Bearer `. For a different audience later, use `getApiCredentials` / `awaitApiCredentials(audience, scope)`, which exchange the refresh token. + +## Biometric-protected credentials + +Pass a `FragmentActivity` and `LocalAuthenticationOptions`: + +```kotlin +val options = LocalAuthenticationOptions.Builder() + .setTitle("Authenticate") + .setDescription("Access your credentials") + .setAuthenticationLevel(AuthenticationLevel.STRONG) + .setNegativeButtonText("Cancel") + .setDeviceCredentialFallback(false) + .setPolicy(BiometricPolicy.Session(300)) + .build() + +val credentialsManager = SecureCredentialsManager(apiClient, context, storage, fragmentActivity, options) +``` + +- `setTitle` is required; `build()` throws without it. +- `AuthenticationLevel`: `STRONG`, `WEAK`, `DEVICE_CREDENTIAL`. +- `BiometricPolicy`: `Always` (default), `Session(timeoutInSeconds)`, `AppLifecycle(timeoutInSeconds = 3600)`. Call `clearBiometricSession()` to force a new prompt. +- `STRONG` with device-credential fallback is rejected on API 28 and 29, and `DEVICE_CREDENTIAL` alone needs API 30+. These surface as `BIOMETRIC_ERROR_*` exceptions. + +## Direct authentication (`AuthenticationAPIClient`) + +Direct calls skip the browser and do not validate the ID token unless you ask. Always chain `.validateClaims()` on requests that return `Credentials`. + +```kotlin +val authentication = AuthenticationAPIClient(account) + +// Database login +authentication.login("user@example.com", "password", "Username-Password-Authentication") + .validateClaims() + .setScope("openid profile email offline_access") + .start(callback) + +// Sign up (creates the user, then logs in) +authentication.signUp("user@example.com", "password", connection = "Username-Password-Authentication") + .validateClaims() + .start(callback) + +// Reset password +authentication.resetPassword("user@example.com", "Username-Password-Authentication") + .start(voidCallback) + +// Passwordless email code: request, then log in +authentication.passwordlessWithEmail("user@example.com", PasswordlessType.CODE, "email") + .start(voidCallback) +authentication.loginWithEmail("user@example.com", "123456", "email") + .validateClaims() + .start(callback) +``` + +- `signUp` returns a `SignUpRequest` that yields `Credentials`, not `Void`. +- Passwordless needs the **Passwordless OTP** grant type on the application. SMS: `passwordlessWithSMS` and `loginWithPhoneNumber`. +- If a login fails with `error.isMultifactorRequired`, continue with the [mfa](./mfa/SKILL.md) skill. +- Direct password login requires the **Password** grant type enabled on the application and the Native app type. + +More: [`examples/authentication-api/`](https://github.com/auth0/Auth0.Android/tree/main/examples/authentication-api). + +## Custom Tabs + +```kotlin +val tabs = CustomTabsOptions.newBuilder() + .withToolbarColor(R.color.toolbar) + .showTitle(true) + .build() + +WebAuthProvider.login(account).withCustomTabsOptions(tabs).start(this, callback) +``` + +Other builder methods: `withBrowserPicker`, `withDisabledCustomTabsPackages`, and partial-sheet options (`withInitialHeight`, `withInitialWidth`, `withResizable`, `withToolbarCornerRadius`, `withSideSheetBreakpoint`, `withBackgroundInteractionEnabled`). See [`examples/custom-tabs-ui.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/custom-tabs-ui.md). + +## Error handling + +`AuthenticationException` exposes `getCode()`, `getDescription()`, `statusCode`, and the flags `isNetworkError`, `isBrowserAppNotAvailable`, `isAuthenticationCanceled`, `isMultifactorRequired`, `isInvalidCredentials`, `isAccessDenied`, `isTooManyAttempts`, `isRefreshTokenDeleted`, `isPasswordNotStrongEnough`, `isIdTokenValidationError`. In Kotlin call `getCode()` and `getDescription()` as functions; `.code` does not compile. Descriptions are for debugging, not UI. + +## Testing + +Unit tests that touch the SDK can fail with `Method getMainLooper in android.os.Looper not mocked`. Use Robolectric, or a JUnit 4 rule that replaces `CommonThreadSwitcher` with a synchronous delegate. See [`examples/unit-testing.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/unit-testing.md). + +Manual checks: login and logout on a device, credentials survive an app restart, refresh works after the access token expires, cancelling the browser calls `onFailure` with `isAuthenticationCanceled`. + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Missing `auth0Domain` / `auth0Scheme` manifest placeholders | Add both to `defaultConfig`. The build fails or the redirect never returns to the app without them. | +| Callback URL not in Allowed Callback URLs and Allowed Logout URLs | Add `{scheme}://{domain}/android/{applicationId}/callback` to both fields. If it is missing the browser stays open. | +| Dashboard application type is not Native | Create a Native application. | +| Custom scheme with uppercase letters, or `withScheme` not matching the placeholder | Android schemes must be lowercase. Use the same value in the placeholder, Dashboard, and `withScheme`. | +| Missing `INTERNET` permission | Add ``. | +| Skipping `.validateClaims()` on `AuthenticationAPIClient` calls that return `Credentials` | Add it. `WebAuthProvider` validates the ID token for you; direct calls do not. | +| Passing `(context, apiClient, storage)` to the credentials manager | The order is `(apiClient, context, storage)`. | +| Reading `error.code` on `CredentialsManagerException`, or `credentials.claims` | Compare to `CredentialsManagerException.NO_CREDENTIALS` etc. Read claims from `credentials.user` (`getExtraInfo()` for custom claims). | +| No `offline_access` scope | Without a refresh token `getCredentials` cannot renew an expired access token. | +| Storing tokens in plain `SharedPreferences`, or logging them | Use `SecureCredentialsManager`. Never log tokens. | +| Login callback lost on rotation or process death | See [`examples/configuration-changes.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/configuration-changes.md). | + +## Troubleshooting + +| Symptom | Cause and fix | +|---------|---------------| +| Browser opens but never returns to the app | Placeholders or callback URL do not match. Rebuild after changing placeholders. For `https`, the Auth0 domain must serve a valid Digital Asset Links file for your app signing certificate. | +| `isBrowserAppNotAvailable` | No Custom Tabs-capable browser. Install one or use another browser on the device. | +| "Invalid state" or login stuck after long idle | The authorization session was lost (process death, long delay). Start login again. | +| `getCredentials` fails with `NO_REFRESH_TOKEN` | Login did not request `offline_access`, or the refresh token was not issued. | +| `getCredentials` fails with `RENEW_FAILED` | Refresh token expired or revoked. Send the user to login. | +| `LARGE_MIN_TTL` | The requested `minTtl` exceeds the access token lifetime. Lower it or raise the API token expiration. | +| Credentials gone after a lock-screen change | Keystore keys were invalidated (`CRYPTO_EXCEPTION`). Log in again. | +| Release build crashes in the SDK | Proguard rules ship with the AAR. If you merge them manually, include `proguard-okio.pro`, `proguard-gson.pro` and `proguard-jetpack.pro` from the [proguard directory](https://github.com/auth0/Auth0.Android/tree/main/proguard). | + +## Security + +- Never put a client secret in the app. Native apps are public clients; `WebAuthProvider` uses PKCE automatically. +- Prefer `https` (App Links) over custom schemes, which can be impersonated. +- Store tokens only through `SecureCredentialsManager`; do not log access, ID, or refresh tokens. +- Prefer `AuthenticationLevel.STRONG` and an explicit `BiometricPolicy` when gating credentials behind biometrics. +- Consider DPoP to bind tokens to the device: [`examples/dpop.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/dpop.md). + +## Quick Reference + +| Class | Purpose | +|-------|---------| +| `Auth0` | Holds client ID and domain | +| `WebAuthProvider` | Universal Login: `login`, `logout` | +| `AuthenticationAPIClient` | Direct API calls, `mfaClient`, passkeys, token exchange | +| `SecureCredentialsManager` / `CredentialsManager` | Store, refresh, and clear credentials | +| `LocalAuthenticationOptions`, `BiometricPolicy`, `AuthenticationLevel` | Biometric gating | +| `MyAccountAPIClient` | My Account API (authentication methods, passkey enrollment) | +| `Credentials` | `idToken`, `accessToken`, `refreshToken`, `expiresAt`, `scope`, `user` | diff --git a/skills/custom-token-exchange/SKILL.md b/skills/custom-token-exchange/SKILL.md new file mode 100644 index 000000000..65b69c4bd --- /dev/null +++ b/skills/custom-token-exchange/SKILL.md @@ -0,0 +1,62 @@ +--- +name: custom-token-exchange +description: >- + Use when exchanging an external or legacy token (subject token) for Auth0 + tokens in an Auth0.Android app with AuthenticationAPIClient.customTokenExchange: + migrating from another identity system, signing in with a token from a trusted + partner, or optionally scoping the exchange to an organization. +metadata: + type: sub-skill + library: Auth0.Android + library_version: 4.3.1 +requires: + - auth0-android +--- + +# Auth0.Android - Custom Token Exchange + +Reference: [`examples/authentication-api/custom-token-exchange.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/authentication-api/custom-token-exchange.md). Tenant setup (a Custom Token Exchange profile and the action that validates the subject token) is configured in Auth0, not in the app. + +## Signature + +```kotlin +fun customTokenExchange( + subjectTokenType: String, + subjectToken: String, + organization: String? = null, + actorToken: ActorToken? = null +): AuthenticationRequest +``` + +The token type comes first, then the token. This is the reverse of `loginWithNativeSocialToken(token, tokenType)`; swapping them compiles and sends the wrong values. + +`actorToken` is for delegation and is not covered here. + +## Exchange a token + +```kotlin +authentication + .customTokenExchange( + subjectTokenType = "urn:acme:legacy-token", // a URI you define for your profile + subjectToken = legacyToken + ) + .validateClaims() + .start(object : Callback { + override fun onSuccess(result: Credentials) { + credentialsManager.saveCredentials(result) + } + + override fun onFailure(error: AuthenticationException) { } + }) +``` + +Coroutines: `.await()` returns `Credentials` and throws `AuthenticationException`. + +To scope the result to an organization, pass `organization = "org_abc123"`. + +## Notes + +- The SDK's own example omits `.validateClaims()`. Keep it; direct `AuthenticationAPIClient` calls do not validate the ID token otherwise. +- Public client: no client secret. Do not build the `/oauth/token` request by hand. +- Do not log or persist the subject token. Save the returned `Credentials` with `SecureCredentialsManager`. +- Use a non-reserved URI for `subjectTokenType`; it must match the profile in the tenant. diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md new file mode 100644 index 000000000..ed29ee719 --- /dev/null +++ b/skills/mfa/SKILL.md @@ -0,0 +1,118 @@ +--- +name: mfa +description: >- + Use when handling multi-factor authentication in an Auth0.Android app: detecting + mfa_required on a password login, listing authenticators, enrolling a phone, + email, OTP or push factor, challenging and verifying with MfaApiClient, recovery + codes, and MFA error handling. Covers the Flexible Factors Grant API in v4. +metadata: + type: sub-skill + library: Auth0.Android + library_version: 4.3.1 +requires: + - auth0-android +--- + +# Auth0.Android - MFA (Flexible Factors Grant) + +Early Access. The application needs the **MFA** grant type (Dashboard, Applications, Advanced Settings, Grant Types); contact your Auth0 representative to enable it. Full reference: [`examples/authentication-api/mfa-flexible-factors.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/authentication-api/mfa-flexible-factors.md). + +The older MFA methods on `AuthenticationAPIClient` were removed in v4. Everything goes through `authentication.mfaClient(mfaToken)`, which returns an `MfaApiClient`. Each call accepts a `Callback` via `.start(...)` or coroutines via `.await()`. + +## Detect mfa_required + +```kotlin +authentication.login("user@example.com", "password", "Username-Password-Authentication") + .setAudience("https://api.example.com") + .setScope("openid profile email") + .validateClaims() + .start(object : Callback { + override fun onSuccess(result: Credentials) { } + + override fun onFailure(error: AuthenticationException) { + if (error.isMultifactorRequired) { + val payload = error.mfaRequiredErrorPayload + val mfaToken = payload?.mfaToken + val enroll = payload?.mfaRequirements?.enroll // List?, user has no factor yet + val challenge = payload?.mfaRequirements?.challenge // List?, user can be challenged + } + } + }) +``` + +`isMultifactorEnrollRequired` is also available when the user must enroll first. `getCode()` and `getDescription()` are functions in Kotlin. + +## MfaApiClient + +| Call | Returns | +|------|---------| +| `getAuthenticators(factorsAllowed: List)` | `Request, MfaListAuthenticatorsException>` (`id`, `type`, `authenticatorType`, `active`, `oobChannel`, `name`) | +| `enroll(MfaEnrollmentType)` | `Request` | +| `challenge(authenticatorId: String)` | `Request` (`challengeType`, `oobCode`, `bindingMethod`) | +| `verify(MfaVerificationType)` | `Request` | + +- `MfaEnrollmentType`: `Phone(phoneNumber)`, `Email(email)`, `Otp`, `Push`. +- `MfaVerificationType`: `Otp(otp)`, `Oob(oobCode, bindingCode = null)`, `RecoveryCode(code)`. +- `factorsAllowed` must be non-empty. Build it from `mfaRequirements.challenge.map { it.type }`. When `challenge` is empty or null, enroll instead. +- `EnrollmentChallenge` is a sealed class. Branch with `when`: `TotpEnrollmentChallenge` (`barcodeUri`, `manualInputCode`, `secret`, `recoveryCodes`), `OobEnrollmentChallenge` (`oobCode`, `bindingMethod`), `RecoveryCodeEnrollmentChallenge`, `MfaEnrollmentChallenge`. Type the callback as `Callback`, not a subtype. +- Exceptions are nested in `MfaException`: import `com.auth0.android.authentication.mfa.MfaException.MfaVerifyException` and so on. + +## Challenge then verify + +`challenge` always requests an out-of-band challenge, which is what sends the SMS, email or push. Call it before verifying an OOB factor. For an authenticator app (`authenticatorType == "otp"`) skip it and verify the code directly. + +```kotlin +val mfaClient = authentication.mfaClient(mfaToken) + +val authenticator = mfaClient + .getAuthenticators(factorsAllowed = requirements.challenge.orEmpty().map { it.type }) + .await() + .first() + +val credentials = if (authenticator.authenticatorType == "otp") { + mfaClient.verify(MfaVerificationType.Otp(userEnteredCode)) +} else { + val challenge = mfaClient.challenge(authenticator.id).await() + mfaClient.verify(MfaVerificationType.Oob(challenge.oobCode!!, bindingCode = userEnteredCode)) +}.await() + +credentialsManager.saveCredentials(credentials) +``` + +For push, the `bindingCode` is optional; omit it once the user approves on their device. + +## Enroll + +```kotlin +when (val enrollment = mfaClient.enroll(MfaEnrollmentType.Otp).await()) { + is TotpEnrollmentChallenge -> { /* show enrollment.barcodeUri or manualInputCode */ } + is OobEnrollmentChallenge -> { /* then verify with MfaVerificationType.Oob(enrollment.oobCode!!, code) */ } + else -> { } +} +``` + +After enrolling an OTP factor, verify with `MfaVerificationType.Otp(code)` to receive credentials. + +## DPoP + +If the `AuthenticationAPIClient` was configured with `useDPoP(context)`, the MFA client inherits it. The DPoP proof is attached to the final `verify` call. + +## Errors + +All four exception types expose `getCode()`, `getDescription()`, `statusCode`, `getValue(key)`, `isNetworkError` and `cause`. Branch on the code, not the description: + +| Code | Meaning | +|------|---------| +| `invalid_token` | MFA token expired or invalid; restart login | +| `invalid_grant`, `invalid_oob_code`, `invalid_binding_code`, `expired_token` | Wrong or expired code | +| `enrollment_conflict` | Authenticator already enrolled | +| `unsupported_challenge_type` | Factor not enabled for the tenant | +| `authenticator_not_found` | Unknown authenticator id | + +## Common mistakes + +- Verifying an OOB factor (SMS, email, push) without calling `challenge` first. +- Calling `getAuthenticators` with an empty list. +- Forgetting `.setAudience` / `.setScope` on the original `login` request, then getting credentials for the wrong API. +- Using removed `AuthenticationAPIClient` MFA methods from v3. +- Typing the enroll callback as a concrete challenge class. diff --git a/skills/organizations/SKILL.md b/skills/organizations/SKILL.md new file mode 100644 index 000000000..527e3ad8c --- /dev/null +++ b/skills/organizations/SKILL.md @@ -0,0 +1,67 @@ +--- +name: organizations +description: >- + Use when building a multi-tenant or B2B Auth0.Android app with Auth0 + Organizations: logging a user into a specific organization with + WebAuthProvider.withOrganization, accepting an organization invitation link with + withInvitationUrl and App Links, reading the org_id claim, or associating a + password reset with an organization. +metadata: + type: sub-skill + library: Auth0.Android + library_version: 4.3.1 +requires: + - auth0-android +--- + +# Auth0.Android - Organizations + +Organizations are available on Enterprise and Startup plans. Reference: [`examples/organizations.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/organizations.md). There is no dedicated organization accessor on `Credentials`. + +## Log in to an organization + +```kotlin +WebAuthProvider.login(account) + .withOrganization("org_abc123") // organization id (starts with org_) or name + .start(this, callback) +``` + +The SDK validates the ID token against the value you pass: an id starting with `org_` is compared to the `org_id` claim, anything else is compared (lowercased) to `org_name`. A mismatch fails the login with a token validation error. + +## Accept an invitation + +Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support) so the link opens your app. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. + +```kotlin +intent?.data?.let { uri -> + WebAuthProvider.login(account) + .withInvitationUrl(uri.toString()) + .start(this, callback) +} +``` + +If the URL lacks the expected values the callback receives an error. + +## Read the organization + +`org_id` and `org_name` are ID token claims. `credentials.user` decodes the ID token, so non-standard claims are in `getExtraInfo()`: + +```kotlin +val orgId = credentials.user.getExtraInfo()["org_id"] as? String +``` + +## Password reset for an organization user + +```kotlin +authentication.resetPassword("user@example.com", "Username-Password-Authentication", "org_abc123") + .start(voidCallback) +``` + +The third argument must be the organization id, not the name. Auth0 adds the organization details to the reset redirect URL and email templates. + +## Notes + +- Enable the organization and the connection on the Auth0 application, and set the application's organization behavior in the Dashboard. +- Keep the client ID and domain in `strings.xml`, read through `Auth0.getInstance(context)`. No client secret in the app. +- Store credentials with `SecureCredentialsManager`. +- Do not build the `/authorize` URL by hand to add `organization`; use the builder. diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md new file mode 100644 index 000000000..5322df03d --- /dev/null +++ b/skills/passkeys/SKILL.md @@ -0,0 +1,110 @@ +--- +name: passkeys +description: >- + Use when adding passkeys to an Auth0.Android app: signing in with a passkey, + signing up a new user with a passkey, or enrolling a passkey for an already + signed-in user through the My Account API. Covers AuthenticationAPIClient + passkeyChallenge, signupWithPasskey, signinWithPasskey, MyAccountAPIClient, the + AndroidX Credential Manager ceremony, and identifier verification on signup. +metadata: + type: sub-skill + library: Auth0.Android + library_version: 4.3.1 +requires: + - auth0-android +--- + +# Auth0.Android - Passkeys + +Reference: [`examples/passkeys.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/passkeys.md) and [`examples/my-account-api.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/my-account-api.md). + +Requirements: a custom domain, the **Passkeys** grant enabled on the application, Android Device Settings configured for the application, and Android 9 (API 28) or higher for passkey calls. The Digital Asset Links file must be served and verified for the custom domain. + +Pattern: Auth0 challenge, then the AndroidX Credential Manager ceremony, then Auth0 sign-in or enroll with the credential. The SDK removed `PasskeyAuthProvider`, `PasskeyProvider` and `PasskeyManager` in v4. + +## Gradle + +Credential Manager is not a dependency of the SDK, and Gson is not exposed on your compile classpath. Add to the app module: + +```groovy +implementation 'androidx.credentials:credentials:1.3.0' +implementation 'androidx.credentials:credentials-play-services-auth:1.3.0' +implementation 'com.google.code.gson:gson:2.11.0' +``` + +`PublicKeyCredentials` is `com.auth0.android.request.PublicKeyCredentials`. + +## Sign in + +```kotlin +val authentication = AuthenticationAPIClient(account) + +val challenge = authentication.passkeyChallenge(realm = "Username-Password-Authentication").await() + +val option = GetPublicKeyCredentialOption(Gson().toJson(challenge.authParamsPublicKey)) +val result = credentialManager.getCredential(context, GetCredentialRequest(listOf(option))) +val response = (result.credential as PublicKeyCredential).authenticationResponseJson + +val credentials = authentication + .signinWithPasskey(challenge.authSession, Gson().fromJson(response, PublicKeyCredentials::class.java), "Username-Password-Authentication") + .validateClaims() + .await() +credentialsManager.saveCredentials(credentials) +``` + +`passkeyChallenge(realm: String? = null, organization: String? = null)`. `signinWithPasskey(authSession, authResponse, realm?, organization?, verification, verificationRequired)`; `authSession` is first. `authResponse` can be a `PublicKeyCredentials` or the raw JSON `String`. + +## Sign up + +```kotlin +val challenge = authentication + .signupWithPasskey(UserData(email = "user@example.com"), realm = "Username-Password-Authentication") + .await() + +val request = CreatePublicKeyCredentialRequest(Gson().toJson(challenge.authParamsPublicKey)) +val created = credentialManager.createCredential(context, request) as CreatePublicKeyCredentialResponse +val response = Gson().fromJson(created.registrationResponseJson, PublicKeyCredentials::class.java) + +val credentials = authentication + .signinWithPasskey(challenge.authSession, response, "Username-Password-Authentication") + .validateClaims() + .await() +``` + +`signupWithPasskey(userData: UserData, realm?, organization?, deliveryMethod?)`. `UserData` is `com.auth0.android.request.UserData`, not a Map. + +### Identifier verification + +If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same auth session and credential. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. + +## Enroll a passkey for a signed-in user + +Uses the same create ceremony, but goes through `MyAccountAPIClient` with a My Account token. It does not create an account and returns no new `Credentials`. + +```kotlin +val api = credentialsManager.awaitApiCredentials( + audience = "https://YOUR_CUSTOM_DOMAIN/me/", + scope = "create:me:authentication_methods" +) + +val myAccount = MyAccountAPIClient(account, api.accessToken) +val challenge = myAccount.passkeyEnrollmentChallenge().await() + +val request = CreatePublicKeyCredentialRequest(Gson().toJson(challenge.authParamsPublicKey)) +val created = credentialManager.createCredential(context, request) as CreatePublicKeyCredentialResponse +val credential = Gson().fromJson(created.registrationResponseJson, PublicKeyCredentials::class.java) + +val method = myAccount.enroll(credential, challenge).await() // PasskeyAuthenticationMethod +``` + +`passkeyEnrollmentChallenge(userIdentity: String? = null, connection: String? = null)` throws `MyAccountException`. Pass `userIdentity` when the user logged in through a linked account. + +## Common mistakes + +- Omitting `.validateClaims()` on `signinWithPasskey`. +- Using the login access token for enrollment instead of one for the `/me/` audience with `create:me:authentication_methods`. +- Calling `signupWithPasskey` to add a passkey to an existing user; that creates a new account. +- Crossing `getCredential` (sign-in) and `createCredential` (signup, enroll). +- Passing the ceremony JSON as the credential without parsing it into `PublicKeyCredentials` (or using the `String` overload). +- Missing or unverified Digital Asset Links on the custom domain; Credential Manager refuses the ceremony. +- Expecting a dedicated MFA exception. If the tenant adds a second factor, `AuthenticationException.isMultifactorRequired` is true; continue with the [mfa](../mfa/SKILL.md) skill. From d8cbb0540288ce23a0561130eb032906f1da16ec Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Tue, 17 Nov 2026 16:09:44 +0530 Subject: [PATCH 2/7] docs(skills): address review feedback on android skills --- skills/SKILL.md | 12 ++++++++++-- skills/mfa/SKILL.md | 5 +++-- skills/organizations/SKILL.md | 4 ++-- skills/passkeys/SKILL.md | 5 +++-- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/skills/SKILL.md b/skills/SKILL.md index f2e568f5f..8af8d87d4 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -78,6 +78,8 @@ https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback `{YOUR_APP_PACKAGE_NAME}` is the `applicationId`. With a custom scheme, replace `https` with it. +For `https`, also register the app for [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`keytool -printcert -jarfile app.apk`). Debug and release builds have different fingerprints. + ### 3. Create the Auth0 instance ```xml @@ -96,6 +98,7 @@ val account = Auth0.getInstance(context) ### 4. Log in and log out ```kotlin +// on login tap WebAuthProvider.login(account) .withScope("openid profile email offline_access") .start(this, object : Callback { @@ -112,6 +115,7 @@ WebAuthProvider.login(account) } }) +// on logout tap, after login has finished; starting logout resets any login in flight WebAuthProvider.logout(account) .start(this, object : Callback { override fun onSuccess(result: Void?) { @@ -152,6 +156,8 @@ if (credentialsManager.hasValidCredentials()) { } } }) +} else { + // no stored session: start WebAuthProvider.login } ``` @@ -207,10 +213,12 @@ authentication.signUp("user@example.com", "password", connection = "Username-Pas authentication.resetPassword("user@example.com", "Username-Password-Authentication") .start(voidCallback) -// Passwordless email code: request, then log in +// Passwordless email code: request the code authentication.passwordlessWithEmail("user@example.com", PasswordlessType.CODE, "email") .start(voidCallback) -authentication.loginWithEmail("user@example.com", "123456", "email") + +// then, once the user types the code they received +authentication.loginWithEmail("user@example.com", userEnteredCode, "email") .validateClaims() .start(callback) ``` diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index ed29ee719..8aa8f17f7 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -67,7 +67,7 @@ val mfaClient = authentication.mfaClient(mfaToken) val authenticator = mfaClient .getAuthenticators(factorsAllowed = requirements.challenge.orEmpty().map { it.type }) .await() - .first() + .first { it.active } // throws if none is active; enroll instead val credentials = if (authenticator.authenticatorType == "otp") { mfaClient.verify(MfaVerificationType.Otp(userEnteredCode)) @@ -76,6 +76,7 @@ val credentials = if (authenticator.authenticatorType == "otp") { mfaClient.verify(MfaVerificationType.Oob(challenge.oobCode!!, bindingCode = userEnteredCode)) }.await() +// verify does not validate the ID token; check the claims you rely on before trusting it credentialsManager.saveCredentials(credentials) ``` @@ -85,7 +86,7 @@ For push, the `bindingCode` is optional; omit it once the user approves on their ```kotlin when (val enrollment = mfaClient.enroll(MfaEnrollmentType.Otp).await()) { - is TotpEnrollmentChallenge -> { /* show enrollment.barcodeUri or manualInputCode */ } + is TotpEnrollmentChallenge -> { /* show enrollment.barcodeUri or enrollment.secret (manualInputCode is only set by My Account) */ } is OobEnrollmentChallenge -> { /* then verify with MfaVerificationType.Oob(enrollment.oobCode!!, code) */ } else -> { } } diff --git a/skills/organizations/SKILL.md b/skills/organizations/SKILL.md index 527e3ad8c..a8217f00e 100644 --- a/skills/organizations/SKILL.md +++ b/skills/organizations/SKILL.md @@ -30,10 +30,10 @@ The SDK validates the ID token against the value you pass: an id starting with ` ## Accept an invitation -Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support) so the link opens your app. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. +Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support) so the link opens your app, and set the application's Application Login URI in the Dashboard to that HTTPS URL so invitations point at it. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. ```kotlin -intent?.data?.let { uri -> +intent?.data?.takeIf { it.isHierarchical }?.let { uri -> // opaque URIs (mailto:) make the SDK throw WebAuthProvider.login(account) .withInvitationUrl(uri.toString()) .start(this, callback) diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md index 5322df03d..a018888d3 100644 --- a/skills/passkeys/SKILL.md +++ b/skills/passkeys/SKILL.md @@ -48,6 +48,7 @@ val response = (result.credential as PublicKeyCredential).authenticationResponse val credentials = authentication .signinWithPasskey(challenge.authSession, Gson().fromJson(response, PublicKeyCredentials::class.java), "Username-Password-Authentication") .validateClaims() + .setScope("openid profile email offline_access") .await() credentialsManager.saveCredentials(credentials) ``` @@ -75,11 +76,11 @@ val credentials = authentication ### Identifier verification -If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same auth session and credential. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. +If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. ## Enroll a passkey for a signed-in user -Uses the same create ceremony, but goes through `MyAccountAPIClient` with a My Account token. It does not create an account and returns no new `Credentials`. +Uses the same create ceremony, but goes through `MyAccountAPIClient` with a My Account token. It does not create an account and returns no new `Credentials`. `awaitApiCredentials` exchanges the refresh token, so sign-in must request `offline_access`. If that refresh token was issued for another audience, Multi-Resource Refresh Token must be configured for the My Account API on the tenant. ```kotlin val api = credentialsManager.awaitApiCredentials( From 1306a6a9560625cf1ab673749993a1957efda159 Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Wed, 18 Nov 2026 09:51:57 +0530 Subject: [PATCH 3/7] docs(skills): fix mfa, passkeys and App Links guidance from review --- skills/SKILL.md | 17 +++++++++++++---- skills/mfa/SKILL.md | 2 +- skills/passkeys/SKILL.md | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/skills/SKILL.md b/skills/SKILL.md index 8af8d87d4..6d485b0b9 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -78,7 +78,7 @@ https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback `{YOUR_APP_PACKAGE_NAME}` is the `applicationId`. With a custom scheme, replace `https` with it. -For `https`, also register the app for [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`keytool -printcert -jarfile app.apk`). Debug and release builds have different fingerprints. +For `https`, also register the app for [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`apksigner verify --print-certs app.apk`). Debug and release builds have different fingerprints. If you use Play App Signing, register the app-signing certificate's SHA-256 from Play Console, not your local upload key, since Play re-signs the APK users install. ### 3. Create the Auth0 instance @@ -115,7 +115,12 @@ WebAuthProvider.login(account) } }) -// on logout tap, after login has finished; starting logout resets any login in flight +``` + +Run logout as a separate action after login has finished. Starting logout resets any login still in flight. + +```kotlin +// on logout tap WebAuthProvider.logout(account) .start(this, object : Callback { override fun onSuccess(result: Void?) { @@ -157,7 +162,7 @@ if (credentialsManager.hasValidCredentials()) { } }) } else { - // no stored session: start WebAuthProvider.login + // no stored session: run the login from step 4 (WebAuthProvider.login(account).start(...)) } ``` @@ -217,7 +222,11 @@ authentication.resetPassword("user@example.com", "Username-Password-Authenticati authentication.passwordlessWithEmail("user@example.com", PasswordlessType.CODE, "email") .start(voidCallback) -// then, once the user types the code they received +``` + +Then, in a separate step once the user types the code they received: + +```kotlin authentication.loginWithEmail("user@example.com", userEnteredCode, "email") .validateClaims() .start(callback) diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index 8aa8f17f7..4b7ee6410 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -67,7 +67,7 @@ val mfaClient = authentication.mfaClient(mfaToken) val authenticator = mfaClient .getAuthenticators(factorsAllowed = requirements.challenge.orEmpty().map { it.type }) .await() - .first { it.active } // throws if none is active; enroll instead + .first { it.active } // throws NoSuchElementException if none is active val credentials = if (authenticator.authenticatorType == "otp") { mfaClient.verify(MfaVerificationType.Otp(userEnteredCode)) diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md index a018888d3..9868c5403 100644 --- a/skills/passkeys/SKILL.md +++ b/skills/passkeys/SKILL.md @@ -76,7 +76,7 @@ val credentials = authentication ### Identifier verification -If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. +If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. If `error.isMultifactorRequired`, continue with the [mfa](../mfa/SKILL.md) skill instead of restarting. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. ## Enroll a passkey for a signed-in user From 0f2f468fd9f87b9535b6ac87ad3914fd7765e046 Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Wed, 18 Nov 2026 12:25:58 +0530 Subject: [PATCH 4/7] docs(skills): fix login flow, push retry and App Links link in skills --- skills/SKILL.md | 36 +++++++++++++++++++---------------- skills/mfa/SKILL.md | 2 +- skills/organizations/SKILL.md | 2 +- skills/passkeys/SKILL.md | 2 +- 4 files changed, 23 insertions(+), 19 deletions(-) diff --git a/skills/SKILL.md b/skills/SKILL.md index 6d485b0b9..18f9045ee 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -78,7 +78,7 @@ https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback `{YOUR_APP_PACKAGE_NAME}` is the `applicationId`. With a custom scheme, replace `https` with it. -For `https`, also register the app for [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`apksigner verify --print-certs app.apk`). Debug and release builds have different fingerprints. If you use Play App Signing, register the app-signing certificate's SHA-256 from Play Console, not your local upload key, since Play re-signs the APK users install. +For `https`, also register the app for [Android App Links](https://auth0.com/docs/get-started/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`apksigner verify --print-certs app.apk`). Debug and release builds have different fingerprints. If you use Play App Signing, register the app-signing certificate's SHA-256 from Play Console, not your local upload key, since Play re-signs the APK users install. ### 3. Create the Auth0 instance @@ -98,23 +98,24 @@ val account = Auth0.getInstance(context) ### 4. Log in and log out ```kotlin -// on login tap -WebAuthProvider.login(account) - .withScope("openid profile email offline_access") - .start(this, object : Callback { - override fun onSuccess(result: Credentials) { - credentialsManager.saveCredentials(result) - } +val loginCallback = object : Callback { + override fun onSuccess(result: Credentials) { + credentialsManager.saveCredentials(result) + } - override fun onFailure(error: AuthenticationException) { - when { - error.isAuthenticationCanceled -> { /* user closed the browser */ } - error.isBrowserAppNotAvailable -> { /* no browser installed */ } - else -> { /* inspect error.getCode() / error.getDescription() */ } - } + override fun onFailure(error: AuthenticationException) { + when { + error.isAuthenticationCanceled -> { /* user closed the browser */ } + error.isBrowserAppNotAvailable -> { /* no browser installed */ } + else -> { /* inspect error.getCode() / error.getDescription() */ } } - }) + } +} +// on login tap +WebAuthProvider.login(account) + .withScope("openid profile email offline_access") + .start(this, loginCallback) ``` Run logout as a separate action after login has finished. Starting logout resets any login still in flight. @@ -162,7 +163,10 @@ if (credentialsManager.hasValidCredentials()) { } }) } else { - // no stored session: run the login from step 4 (WebAuthProvider.login(account).start(...)) + // no stored session: start the login from step 4 + WebAuthProvider.login(account) + .withScope("openid profile email offline_access") + .start(this, loginCallback) } ``` diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index 4b7ee6410..e6682a111 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -80,7 +80,7 @@ val credentials = if (authenticator.authenticatorType == "otp") { credentialsManager.saveCredentials(credentials) ``` -For push, the `bindingCode` is optional; omit it once the user approves on their device. +For push, the `bindingCode` is optional; omit it once the user approves on their device. Until then the server can answer `verify` with `authorization_pending`, which is Auth0 server behaviour and not defined in this SDK. Check `MfaVerifyException.getCode()`, retry the same `verify` after a short delay, and wait longer on `slow_down`. ## Enroll diff --git a/skills/organizations/SKILL.md b/skills/organizations/SKILL.md index a8217f00e..23d37a00e 100644 --- a/skills/organizations/SKILL.md +++ b/skills/organizations/SKILL.md @@ -30,7 +30,7 @@ The SDK validates the ID token against the value you pass: an id starting with ` ## Accept an invitation -Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/applications/enable-android-app-links-support) so the link opens your app, and set the application's Application Login URI in the Dashboard to that HTTPS URL so invitations point at it. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. +Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/get-started/applications/enable-android-app-links-support) so the link opens your app, and set the application's Application Login URI in the Dashboard to that HTTPS URL so invitations point at it. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. ```kotlin intent?.data?.takeIf { it.isHierarchical }?.let { uri -> // opaque URIs (mailto:) make the SDK throw diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md index 9868c5403..ac0fb5b4e 100644 --- a/skills/passkeys/SKILL.md +++ b/skills/passkeys/SKILL.md @@ -76,7 +76,7 @@ val credentials = authentication ### Identifier verification -If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. If `error.isMultifactorRequired`, continue with the [mfa](../mfa/SKILL.md) skill instead of restarting. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. +If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` (it is null when the server omits them, so fall back to `challenge.verificationRequired`) and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. If `error.isMultifactorRequired`, continue with the [mfa](../mfa/SKILL.md) skill instead of restarting. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. ## Enroll a passkey for a signed-in user From 43a16ad91bc1da8f81eb244f1804079a70c97d4f Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Wed, 18 Nov 2026 13:18:44 +0530 Subject: [PATCH 5/7] docs(skills): register callbacks, add audience and fix push binding code --- skills/SKILL.md | 21 ++++++++++++++------- skills/mfa/SKILL.md | 4 +++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/skills/SKILL.md b/skills/SKILL.md index 18f9045ee..2b2d71403 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -112,9 +112,21 @@ val loginCallback = object : Callback { } } +val logoutCallback = object : Callback { + override fun onSuccess(result: Void?) { + credentialsManager.clearCredentials() + } + + override fun onFailure(error: AuthenticationException) { } +} + +// in onCreate: keeps results from being lost if the Activity is recreated while the browser is open +WebAuthProvider.registerCallbacks(this, loginCallback, logoutCallback) + // on login tap WebAuthProvider.login(account) .withScope("openid profile email offline_access") + // .withAudience("YOUR_API_IDENTIFIER") // if the app calls an API, see step 6 .start(this, loginCallback) ``` @@ -123,13 +135,7 @@ Run logout as a separate action after login has finished. Starting logout resets ```kotlin // on logout tap WebAuthProvider.logout(account) - .start(this, object : Callback { - override fun onSuccess(result: Void?) { - credentialsManager.clearCredentials() - } - - override fun onFailure(error: AuthenticationException) { } - }) + .start(this, logoutCallback) ``` Coroutines: `WebAuthProvider.login(account).await(context)` returns `Credentials` and `WebAuthProvider.logout(account).await(context)` returns `Unit`; both throw `AuthenticationException`. @@ -166,6 +172,7 @@ if (credentialsManager.hasValidCredentials()) { // no stored session: start the login from step 4 WebAuthProvider.login(account) .withScope("openid profile email offline_access") + // .withAudience("YOUR_API_IDENTIFIER") // same audience as step 4 .start(this, loginCallback) } ``` diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index e6682a111..bf98ea4f1 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -73,7 +73,9 @@ val credentials = if (authenticator.authenticatorType == "otp") { mfaClient.verify(MfaVerificationType.Otp(userEnteredCode)) } else { val challenge = mfaClient.challenge(authenticator.id).await() - mfaClient.verify(MfaVerificationType.Oob(challenge.oobCode!!, bindingCode = userEnteredCode)) + // bindingMethod is "prompt" when the user must type a code; push has none + val bindingCode = if (challenge.bindingMethod == "prompt") userEnteredCode else null + mfaClient.verify(MfaVerificationType.Oob(challenge.oobCode!!, bindingCode)) }.await() // verify does not validate the ID token; check the claims you rely on before trusting it From 404dcf14310b966113ea881063c4375f9e69f996 Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Thu, 3 Dec 2026 14:01:03 +0530 Subject: [PATCH 6/7] docs(skills): cut the Android skills to verified gotchas with Verify steps Keep only places where the SDK surprises an agent, each checked against the 4.3.1 source; setup and code stay in README.md and examples/. Drop the organizations and custom-token-exchange skills, which had no SDK-specific gotcha beyond what the examples cover. Co-Authored-By: Claude --- CLAUDE.md | 2 +- skills/SKILL.md | 365 ++++---------------------- skills/custom-token-exchange/SKILL.md | 62 ----- skills/mfa/SKILL.md | 133 ++-------- skills/organizations/SKILL.md | 67 ----- skills/passkeys/SKILL.md | 138 +++------- 6 files changed, 111 insertions(+), 656 deletions(-) delete mode 100644 skills/custom-token-exchange/SKILL.md delete mode 100644 skills/organizations/SKILL.md diff --git a/CLAUDE.md b/CLAUDE.md index e1dcd1ef1..3d49d0b2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -138,4 +138,4 @@ See [references/docs-update.md](references/docs-update.md) for the full code-to- ## Agent Skills -For task-specific integration guidance (setup, login, credentials, MFA, passkeys, organizations, custom token exchange), read [`skills/SKILL.md`](skills/SKILL.md) and its sub-skills. They are not packaged in the AAR; consumers read them from the GitHub repo (`auth0/Auth0.Android`, `skills/`). Keep them in sync with `README.md` and `examples/` when public API changes. +For the integration gotchas (login, credentials, MFA, passkeys), read [`skills/SKILL.md`](skills/SKILL.md) and its sub-skills. They are not packaged in the AAR; consumers read them from the GitHub repo (`auth0/Auth0.Android`, `skills/`). Keep them in sync with `README.md` and `examples/` when public API changes. diff --git a/skills/SKILL.md b/skills/SKILL.md index 2b2d71403..c8990a947 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -1,323 +1,62 @@ --- name: auth0-android description: >- - Use when adding Auth0 authentication to a native Android app (Kotlin or Java) - with the com.auth0.android:auth0 SDK: Gradle install, manifest placeholders and - callback URLs, WebAuthProvider login and logout, storing and refreshing tokens - with SecureCredentialsManager (including biometric protection), database - login, signup, passwordless, password reset, Custom Tabs, error handling, and - unit testing. Entry point for all Auth0.Android skills; use it even if the user - only says "add login to my Android app". + Use when adding or changing Auth0 login in a native Android app with the + com.auth0.android:auth0 SDK, even if the user only says "add login to my + Android app". Lists where this SDK behaves differently from what you would + expect; the README and examples/ hold the how-to. metadata: - type: core library: Auth0.Android library_version: 4.3.1 --- # Auth0.Android -Native Android authentication with `com.auth0.android:auth0` (v4, `minSdk` 26, Java 17). - -These skills are not packaged in the AAR. Read them from the GitHub repo: `skills/` in [auth0/Auth0.Android](https://github.com/auth0/Auth0.Android/tree/main/skills). Deeper docs live in the same repo: [`EXAMPLES.md`](https://github.com/auth0/Auth0.Android/blob/main/EXAMPLES.md) indexes `examples/*.md` (one file per feature, Kotlin and Java). Raw URLs work too: `https://raw.githubusercontent.com/auth0/Auth0.Android/main/examples/.md`. - -## Sub-skills - -| Task | Sub-skill | -|------|-----------| -| `mfa_required` handling, enroll, challenge, verify with `MfaApiClient` | [mfa/SKILL.md](./mfa/SKILL.md) | -| Passkey sign-in, signup, and enrollment with Credential Manager | [passkeys/SKILL.md](./passkeys/SKILL.md) | -| Organization login, invitations, reading `org_id` | [organizations/SKILL.md](./organizations/SKILL.md) | -| Exchange an external token for Auth0 tokens | [custom-token-exchange/SKILL.md](./custom-token-exchange/SKILL.md) | - -For DPoP, My Account API, Native to Web SSO, PAR, Auth Tab and other features, see the matching file under `examples/` (linked from `EXAMPLES.md`). - -## Prerequisites - -- Android `minSdk` 26+ and Java 17 (apps below API 26 must stay on the v3 line) -- An Auth0 application of type **Native** - -## Quick Start - -### 1. Install - -```groovy -// app/build.gradle -android { - compileOptions { - sourceCompatibility JavaVersion.VERSION_17 - targetCompatibility JavaVersion.VERSION_17 - } - kotlinOptions { jvmTarget = '17' } -} - -dependencies { - implementation 'com.auth0.android:auth0:4.3.1' -} -``` - -Check [Releases](https://github.com/auth0/Auth0.Android/releases) for the latest version. - -### 2. Configure the manifest - -```xml - -``` - -```groovy -// app/build.gradle, inside android { defaultConfig { ... } } -manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "https"] -``` - -`auth0Domain` and `auth0Scheme` are required: the library uses them to register the redirect intent-filter. `auth0Scheme` is `https` (Android App Links) or a lowercase custom scheme. - -In the Auth0 Dashboard, add this URL to both **Allowed Callback URLs** and **Allowed Logout URLs**: - -``` -https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback -``` - -`{YOUR_APP_PACKAGE_NAME}` is the `applicationId`. With a custom scheme, replace `https` with it. - -For `https`, also register the app for [Android App Links](https://auth0.com/docs/get-started/applications/enable-android-app-links-support): in the application's Device Settings in the Dashboard, add the package name and the SHA256 fingerprint of the signing certificate (`apksigner verify --print-certs app.apk`). Debug and release builds have different fingerprints. If you use Play App Signing, register the app-signing certificate's SHA-256 from Play Console, not your local upload key, since Play re-signs the APK users install. - -### 3. Create the Auth0 instance - -```xml - -YOUR_CLIENT_ID -YOUR_DOMAIN -``` - -```kotlin -val account = Auth0.getInstance(context) -// or: Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN") -``` - -`getInstance(context)` throws `IllegalArgumentException` if either string resource is missing. - -### 4. Log in and log out - -```kotlin -val loginCallback = object : Callback { - override fun onSuccess(result: Credentials) { - credentialsManager.saveCredentials(result) - } - - override fun onFailure(error: AuthenticationException) { - when { - error.isAuthenticationCanceled -> { /* user closed the browser */ } - error.isBrowserAppNotAvailable -> { /* no browser installed */ } - else -> { /* inspect error.getCode() / error.getDescription() */ } - } - } -} - -val logoutCallback = object : Callback { - override fun onSuccess(result: Void?) { - credentialsManager.clearCredentials() - } - - override fun onFailure(error: AuthenticationException) { } -} - -// in onCreate: keeps results from being lost if the Activity is recreated while the browser is open -WebAuthProvider.registerCallbacks(this, loginCallback, logoutCallback) - -// on login tap -WebAuthProvider.login(account) - .withScope("openid profile email offline_access") - // .withAudience("YOUR_API_IDENTIFIER") // if the app calls an API, see step 6 - .start(this, loginCallback) -``` - -Run logout as a separate action after login has finished. Starting logout resets any login still in flight. - -```kotlin -// on logout tap -WebAuthProvider.logout(account) - .start(this, logoutCallback) -``` - -Coroutines: `WebAuthProvider.login(account).await(context)` returns `Credentials` and `WebAuthProvider.logout(account).await(context)` returns `Unit`; both throw `AuthenticationException`. - -Builder options on `login`: `withScope`, `withAudience`, `withConnection`, `withConnectionScope`, `withOrganization`, `withInvitationUrl`, `withParameters` (for example `mapOf("prompt" to "login")`), `withScheme`, `withRedirectUri`, `withCustomTabsOptions`, `withEphemeralBrowsing`, `withTrustedWebActivity`, `withAuthTab`, `withMaxAge`, `withNonce`, `withState`. The default scope is `openid profile email`; `openid` is always enforced. Details: [`examples/web-auth-configuration.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/web-auth-configuration.md). - -Use a custom scheme only if you did not set `auth0Scheme` to `https`: set the placeholder, add the callback URL in the Dashboard, and call `.withScheme("myapp")` on both `login` and `logout`. - -### 5. Store and use credentials - -```kotlin -val apiClient = AuthenticationAPIClient(account) -val storage = SharedPreferencesStorage(context) -val credentialsManager = SecureCredentialsManager(apiClient, context, storage) - -credentialsManager.saveCredentials(credentials) - -if (credentialsManager.hasValidCredentials()) { - credentialsManager.getCredentials(object : Callback { - override fun onSuccess(result: Credentials) { - val accessToken = result.accessToken // refreshed automatically if expired - } - - override fun onFailure(error: CredentialsManagerException) { - when (error) { - CredentialsManagerException.NO_CREDENTIALS, - CredentialsManagerException.NO_REFRESH_TOKEN, - CredentialsManagerException.RENEW_FAILED -> { /* send the user to login */ } - else -> { /* see examples/credentials-manager.md */ } - } - } - }) -} else { - // no stored session: start the login from step 4 - WebAuthProvider.login(account) - .withScope("openid profile email offline_access") - // .withAudience("YOUR_API_IDENTIFIER") // same audience as step 4 - .start(this, loginCallback) -} -``` - -Coroutines: `credentialsManager.awaitCredentials()` throws `CredentialsManagerException`. Refresh needs a refresh token, so request `offline_access`. `CredentialsManager(apiClient, storage)` stores without encryption; prefer `SecureCredentialsManager`. In v4, `clearCredentials()` calls `Storage.removeAll()`, so it wipes everything in that storage, API credentials included; use a dedicated storage name if you share it. Full reference: [`examples/credentials-manager.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/credentials-manager.md). - -`CredentialsManagerException` has no string `code`. Compare against its companion constants (`NO_CREDENTIALS`, `NO_REFRESH_TOKEN`, `RENEW_FAILED`, `STORE_FAILED`, `DPOP_KEY_MISSING`, `SESSION_EXPIRED`, the `BIOMETRIC_*` family, and so on). `isDeviceIncompatible` is true on devices missing required crypto algorithms. - -### 6. Call an API - -Request the API audience at login with `.withAudience("https://api.example.com")`, then attach `credentials.accessToken` as `Authorization: Bearer `. For a different audience later, use `getApiCredentials` / `awaitApiCredentials(audience, scope)`, which exchange the refresh token. - -## Biometric-protected credentials - -Pass a `FragmentActivity` and `LocalAuthenticationOptions`: - -```kotlin -val options = LocalAuthenticationOptions.Builder() - .setTitle("Authenticate") - .setDescription("Access your credentials") - .setAuthenticationLevel(AuthenticationLevel.STRONG) - .setNegativeButtonText("Cancel") - .setDeviceCredentialFallback(false) - .setPolicy(BiometricPolicy.Session(300)) - .build() - -val credentialsManager = SecureCredentialsManager(apiClient, context, storage, fragmentActivity, options) -``` - -- `setTitle` is required; `build()` throws without it. -- `AuthenticationLevel`: `STRONG`, `WEAK`, `DEVICE_CREDENTIAL`. -- `BiometricPolicy`: `Always` (default), `Session(timeoutInSeconds)`, `AppLifecycle(timeoutInSeconds = 3600)`. Call `clearBiometricSession()` to force a new prompt. -- `STRONG` with device-credential fallback is rejected on API 28 and 29, and `DEVICE_CREDENTIAL` alone needs API 30+. These surface as `BIOMETRIC_ERROR_*` exceptions. - -## Direct authentication (`AuthenticationAPIClient`) - -Direct calls skip the browser and do not validate the ID token unless you ask. Always chain `.validateClaims()` on requests that return `Credentials`. - -```kotlin -val authentication = AuthenticationAPIClient(account) - -// Database login -authentication.login("user@example.com", "password", "Username-Password-Authentication") - .validateClaims() - .setScope("openid profile email offline_access") - .start(callback) - -// Sign up (creates the user, then logs in) -authentication.signUp("user@example.com", "password", connection = "Username-Password-Authentication") - .validateClaims() - .start(callback) - -// Reset password -authentication.resetPassword("user@example.com", "Username-Password-Authentication") - .start(voidCallback) - -// Passwordless email code: request the code -authentication.passwordlessWithEmail("user@example.com", PasswordlessType.CODE, "email") - .start(voidCallback) - -``` - -Then, in a separate step once the user types the code they received: - -```kotlin -authentication.loginWithEmail("user@example.com", userEnteredCode, "email") - .validateClaims() - .start(callback) -``` - -- `signUp` returns a `SignUpRequest` that yields `Credentials`, not `Void`. -- Passwordless needs the **Passwordless OTP** grant type on the application. SMS: `passwordlessWithSMS` and `loginWithPhoneNumber`. -- If a login fails with `error.isMultifactorRequired`, continue with the [mfa](./mfa/SKILL.md) skill. -- Direct password login requires the **Password** grant type enabled on the application and the Native app type. - -More: [`examples/authentication-api/`](https://github.com/auth0/Auth0.Android/tree/main/examples/authentication-api). - -## Custom Tabs - -```kotlin -val tabs = CustomTabsOptions.newBuilder() - .withToolbarColor(R.color.toolbar) - .showTitle(true) - .build() - -WebAuthProvider.login(account).withCustomTabsOptions(tabs).start(this, callback) -``` - -Other builder methods: `withBrowserPicker`, `withDisabledCustomTabsPackages`, and partial-sheet options (`withInitialHeight`, `withInitialWidth`, `withResizable`, `withToolbarCornerRadius`, `withSideSheetBreakpoint`, `withBackgroundInteractionEnabled`). See [`examples/custom-tabs-ui.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/custom-tabs-ui.md). - -## Error handling - -`AuthenticationException` exposes `getCode()`, `getDescription()`, `statusCode`, and the flags `isNetworkError`, `isBrowserAppNotAvailable`, `isAuthenticationCanceled`, `isMultifactorRequired`, `isInvalidCredentials`, `isAccessDenied`, `isTooManyAttempts`, `isRefreshTokenDeleted`, `isPasswordNotStrongEnough`, `isIdTokenValidationError`. In Kotlin call `getCode()` and `getDescription()` as functions; `.code` does not compile. Descriptions are for debugging, not UI. - -## Testing - -Unit tests that touch the SDK can fail with `Method getMainLooper in android.os.Looper not mocked`. Use Robolectric, or a JUnit 4 rule that replaces `CommonThreadSwitcher` with a synchronous delegate. See [`examples/unit-testing.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/unit-testing.md). - -Manual checks: login and logout on a device, credentials survive an app restart, refresh works after the access token expires, cancelling the browser calls `onFailure` with `isAuthenticationCanceled`. - -## Common Mistakes - -| Mistake | Fix | -|---------|-----| -| Missing `auth0Domain` / `auth0Scheme` manifest placeholders | Add both to `defaultConfig`. The build fails or the redirect never returns to the app without them. | -| Callback URL not in Allowed Callback URLs and Allowed Logout URLs | Add `{scheme}://{domain}/android/{applicationId}/callback` to both fields. If it is missing the browser stays open. | -| Dashboard application type is not Native | Create a Native application. | -| Custom scheme with uppercase letters, or `withScheme` not matching the placeholder | Android schemes must be lowercase. Use the same value in the placeholder, Dashboard, and `withScheme`. | -| Missing `INTERNET` permission | Add ``. | -| Skipping `.validateClaims()` on `AuthenticationAPIClient` calls that return `Credentials` | Add it. `WebAuthProvider` validates the ID token for you; direct calls do not. | -| Passing `(context, apiClient, storage)` to the credentials manager | The order is `(apiClient, context, storage)`. | -| Reading `error.code` on `CredentialsManagerException`, or `credentials.claims` | Compare to `CredentialsManagerException.NO_CREDENTIALS` etc. Read claims from `credentials.user` (`getExtraInfo()` for custom claims). | -| No `offline_access` scope | Without a refresh token `getCredentials` cannot renew an expired access token. | -| Storing tokens in plain `SharedPreferences`, or logging them | Use `SecureCredentialsManager`. Never log tokens. | -| Login callback lost on rotation or process death | See [`examples/configuration-changes.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/configuration-changes.md). | - -## Troubleshooting - -| Symptom | Cause and fix | -|---------|---------------| -| Browser opens but never returns to the app | Placeholders or callback URL do not match. Rebuild after changing placeholders. For `https`, the Auth0 domain must serve a valid Digital Asset Links file for your app signing certificate. | -| `isBrowserAppNotAvailable` | No Custom Tabs-capable browser. Install one or use another browser on the device. | -| "Invalid state" or login stuck after long idle | The authorization session was lost (process death, long delay). Start login again. | -| `getCredentials` fails with `NO_REFRESH_TOKEN` | Login did not request `offline_access`, or the refresh token was not issued. | -| `getCredentials` fails with `RENEW_FAILED` | Refresh token expired or revoked. Send the user to login. | -| `LARGE_MIN_TTL` | The requested `minTtl` exceeds the access token lifetime. Lower it or raise the API token expiration. | -| Credentials gone after a lock-screen change | Keystore keys were invalidated (`CRYPTO_EXCEPTION`). Log in again. | -| Release build crashes in the SDK | Proguard rules ship with the AAR. If you merge them manually, include `proguard-okio.pro`, `proguard-gson.pro` and `proguard-jetpack.pro` from the [proguard directory](https://github.com/auth0/Auth0.Android/tree/main/proguard). | - -## Security - -- Never put a client secret in the app. Native apps are public clients; `WebAuthProvider` uses PKCE automatically. -- Prefer `https` (App Links) over custom schemes, which can be impersonated. -- Store tokens only through `SecureCredentialsManager`; do not log access, ID, or refresh tokens. -- Prefer `AuthenticationLevel.STRONG` and an explicit `BiometricPolicy` when gating credentials behind biometrics. -- Consider DPoP to bind tokens to the device: [`examples/dpop.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/dpop.md). - -## Quick Reference - -| Class | Purpose | -|-------|---------| -| `Auth0` | Holds client ID and domain | -| `WebAuthProvider` | Universal Login: `login`, `logout` | -| `AuthenticationAPIClient` | Direct API calls, `mfaClient`, passkeys, token exchange | -| `SecureCredentialsManager` / `CredentialsManager` | Store, refresh, and clear credentials | -| `LocalAuthenticationOptions`, `BiometricPolicy`, `AuthenticationLevel` | Biometric gating | -| `MyAccountAPIClient` | My Account API (authentication methods, passkey enrollment) | -| `Credentials` | `idToken`, `accessToken`, `refreshToken`, `expiresAt`, `scope`, `user` | +Follow [README.md](../README.md) and [examples/](../examples/) for setup and +code. This file lists only where the SDK surprises agents. Each item cites the +source at the version above. + +## Gotchas + +- **`withScope()` replaces the default scope.** The default is + `openid profile email`, with no `offline_access`, so no refresh token is + stored. Once the access token expires, `getCredentials` fails with + `CredentialsManagerException.NO_REFRESH_TOKEN`. Pass the full scope, including + `offline_access`, whenever the app keeps a session. + (`WebAuthProvider.kt` `withScope`; `CredentialsManagerException.kt`) +- **Only Web Auth validates the ID token.** `AuthenticationAPIClient` requests + skip validation unless you call `.validateClaims()`, and skipping it only logs + an error. Call it on every request that returns `Credentials`. + (`BaseAuthenticationRequest.kt` `validateClaims`) +- **Login and logout each default to the `https` scheme.** If the app uses a + custom scheme, call `.withScheme()` on the logout builder too, not only on + login. With `https`, the callback only reaches the app once Android App Links + are verified for it. (`WebAuthProvider.kt` `withScheme`) +- **`Credentials` has no claims map.** Read the user's claims from + `credentials.user`; custom claims are in `credentials.user.getExtraInfo()`. + (`Credentials.kt` `user`; `UserProfile.kt` `getExtraInfo`) +- **README's first snippet hardcodes the client ID and domain.** Put them in + `strings.xml` and use `Auth0.getInstance(context)`, so they match the + `auth0Domain` manifest placeholder. (`README.md` "Alternatively") +- **`customTokenExchange(subjectTokenType, subjectToken)` takes the type + first**, the reverse of `loginWithNativeSocialToken(token, tokenType)`. Both + are strings, so a swap compiles and fails at runtime. + (`AuthenticationAPIClient.kt` `customTokenExchange`) +- **Starting any Web Auth flow drops the one in progress.** A logout started + while a login is pending cancels that login without a callback. + (`WebAuthProvider.kt` `resetManagerInstance`) + +For MFA, read [mfa/SKILL.md](mfa/SKILL.md). For passkeys, read +[passkeys/SKILL.md](passkeys/SKILL.md). + +## Verify + +- `./gradlew assembleDebug` passes. +- Every `AuthenticationAPIClient` call that returns `Credentials` has + `.validateClaims()`. +- If the app stores credentials, the login scope includes `offline_access`. +- The callback and logout URLs in the Auth0 application are + `{scheme}://{domain}/android/{applicationId}/callback`. +- Waiting on the developer: sign in on a device, then call `getCredentials` + with a `minTtl` longer than the access token's lifetime and confirm it + returns renewed credentials. diff --git a/skills/custom-token-exchange/SKILL.md b/skills/custom-token-exchange/SKILL.md deleted file mode 100644 index 65b69c4bd..000000000 --- a/skills/custom-token-exchange/SKILL.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: custom-token-exchange -description: >- - Use when exchanging an external or legacy token (subject token) for Auth0 - tokens in an Auth0.Android app with AuthenticationAPIClient.customTokenExchange: - migrating from another identity system, signing in with a token from a trusted - partner, or optionally scoping the exchange to an organization. -metadata: - type: sub-skill - library: Auth0.Android - library_version: 4.3.1 -requires: - - auth0-android ---- - -# Auth0.Android - Custom Token Exchange - -Reference: [`examples/authentication-api/custom-token-exchange.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/authentication-api/custom-token-exchange.md). Tenant setup (a Custom Token Exchange profile and the action that validates the subject token) is configured in Auth0, not in the app. - -## Signature - -```kotlin -fun customTokenExchange( - subjectTokenType: String, - subjectToken: String, - organization: String? = null, - actorToken: ActorToken? = null -): AuthenticationRequest -``` - -The token type comes first, then the token. This is the reverse of `loginWithNativeSocialToken(token, tokenType)`; swapping them compiles and sends the wrong values. - -`actorToken` is for delegation and is not covered here. - -## Exchange a token - -```kotlin -authentication - .customTokenExchange( - subjectTokenType = "urn:acme:legacy-token", // a URI you define for your profile - subjectToken = legacyToken - ) - .validateClaims() - .start(object : Callback { - override fun onSuccess(result: Credentials) { - credentialsManager.saveCredentials(result) - } - - override fun onFailure(error: AuthenticationException) { } - }) -``` - -Coroutines: `.await()` returns `Credentials` and throws `AuthenticationException`. - -To scope the result to an organization, pass `organization = "org_abc123"`. - -## Notes - -- The SDK's own example omits `.validateClaims()`. Keep it; direct `AuthenticationAPIClient` calls do not validate the ID token otherwise. -- Public client: no client secret. Do not build the `/oauth/token` request by hand. -- Do not log or persist the subject token. Save the returned `Credentials` with `SecureCredentialsManager`. -- Use a non-reserved URI for `subjectTokenType`; it must match the profile in the tenant. diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index bf98ea4f1..f5107c9ce 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -1,121 +1,36 @@ --- -name: mfa +name: auth0-android-mfa description: >- - Use when handling multi-factor authentication in an Auth0.Android app: detecting - mfa_required on a password login, listing authenticators, enrolling a phone, - email, OTP or push factor, challenging and verifying with MfaApiClient, recovery - codes, and MFA error handling. Covers the Flexible Factors Grant API in v4. + Use when adding multi-factor authentication to an Android app that uses + com.auth0.android:auth0, including handling mfa_required with the MFA API. metadata: - type: sub-skill library: Auth0.Android library_version: 4.3.1 -requires: - - auth0-android --- -# Auth0.Android - MFA (Flexible Factors Grant) +# MFA with Auth0.Android -Early Access. The application needs the **MFA** grant type (Dashboard, Applications, Advanced Settings, Grant Types); contact your Auth0 representative to enable it. Full reference: [`examples/authentication-api/mfa-flexible-factors.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/authentication-api/mfa-flexible-factors.md). +Follow +[examples/authentication-api/mfa-flexible-factors.md](../../examples/authentication-api/mfa-flexible-factors.md) +for the code. These are the places agents go wrong. -The older MFA methods on `AuthenticationAPIClient` were removed in v4. Everything goes through `authentication.mfaClient(mfaToken)`, which returns an `MfaApiClient`. Each call accepts a `Callback` via `.start(...)` or coroutines via `.await()`. +## Gotchas -## Detect mfa_required +- **Use `authentication.mfaClient(mfaToken)`.** Version 4 removed + `loginWithOTP`, `loginWithOOB`, `loginWithRecoveryCode` and + `multifactorChallenge`; don't call them or hand-build `/oauth/token` MFA + requests. ([V4_MIGRATION_GUIDE.md](../../V4_MIGRATION_GUIDE.md)) +- **`mfaClient(...).verify()` doesn't validate the ID token**, and it has no + `validateClaims()`. Don't trust its ID token claims for access decisions. + (`MfaApiClient.kt` `verify`) +- **The SDK doesn't wait for push approval.** It has no polling, so call + `verify` again on an interval while `error.getCode()` is + `authorization_pending`, and stop on success or any other error. + ([Auth0 docs](https://auth0.com/docs/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators)) -```kotlin -authentication.login("user@example.com", "password", "Username-Password-Authentication") - .setAudience("https://api.example.com") - .setScope("openid profile email") - .validateClaims() - .start(object : Callback { - override fun onSuccess(result: Credentials) { } +## Verify - override fun onFailure(error: AuthenticationException) { - if (error.isMultifactorRequired) { - val payload = error.mfaRequiredErrorPayload - val mfaToken = payload?.mfaToken - val enroll = payload?.mfaRequirements?.enroll // List?, user has no factor yet - val challenge = payload?.mfaRequirements?.challenge // List?, user can be challenged - } - } - }) -``` - -`isMultifactorEnrollRequired` is also available when the user must enroll first. `getCode()` and `getDescription()` are functions in Kotlin. - -## MfaApiClient - -| Call | Returns | -|------|---------| -| `getAuthenticators(factorsAllowed: List)` | `Request, MfaListAuthenticatorsException>` (`id`, `type`, `authenticatorType`, `active`, `oobChannel`, `name`) | -| `enroll(MfaEnrollmentType)` | `Request` | -| `challenge(authenticatorId: String)` | `Request` (`challengeType`, `oobCode`, `bindingMethod`) | -| `verify(MfaVerificationType)` | `Request` | - -- `MfaEnrollmentType`: `Phone(phoneNumber)`, `Email(email)`, `Otp`, `Push`. -- `MfaVerificationType`: `Otp(otp)`, `Oob(oobCode, bindingCode = null)`, `RecoveryCode(code)`. -- `factorsAllowed` must be non-empty. Build it from `mfaRequirements.challenge.map { it.type }`. When `challenge` is empty or null, enroll instead. -- `EnrollmentChallenge` is a sealed class. Branch with `when`: `TotpEnrollmentChallenge` (`barcodeUri`, `manualInputCode`, `secret`, `recoveryCodes`), `OobEnrollmentChallenge` (`oobCode`, `bindingMethod`), `RecoveryCodeEnrollmentChallenge`, `MfaEnrollmentChallenge`. Type the callback as `Callback`, not a subtype. -- Exceptions are nested in `MfaException`: import `com.auth0.android.authentication.mfa.MfaException.MfaVerifyException` and so on. - -## Challenge then verify - -`challenge` always requests an out-of-band challenge, which is what sends the SMS, email or push. Call it before verifying an OOB factor. For an authenticator app (`authenticatorType == "otp"`) skip it and verify the code directly. - -```kotlin -val mfaClient = authentication.mfaClient(mfaToken) - -val authenticator = mfaClient - .getAuthenticators(factorsAllowed = requirements.challenge.orEmpty().map { it.type }) - .await() - .first { it.active } // throws NoSuchElementException if none is active - -val credentials = if (authenticator.authenticatorType == "otp") { - mfaClient.verify(MfaVerificationType.Otp(userEnteredCode)) -} else { - val challenge = mfaClient.challenge(authenticator.id).await() - // bindingMethod is "prompt" when the user must type a code; push has none - val bindingCode = if (challenge.bindingMethod == "prompt") userEnteredCode else null - mfaClient.verify(MfaVerificationType.Oob(challenge.oobCode!!, bindingCode)) -}.await() - -// verify does not validate the ID token; check the claims you rely on before trusting it -credentialsManager.saveCredentials(credentials) -``` - -For push, the `bindingCode` is optional; omit it once the user approves on their device. Until then the server can answer `verify` with `authorization_pending`, which is Auth0 server behaviour and not defined in this SDK. Check `MfaVerifyException.getCode()`, retry the same `verify` after a short delay, and wait longer on `slow_down`. - -## Enroll - -```kotlin -when (val enrollment = mfaClient.enroll(MfaEnrollmentType.Otp).await()) { - is TotpEnrollmentChallenge -> { /* show enrollment.barcodeUri or enrollment.secret (manualInputCode is only set by My Account) */ } - is OobEnrollmentChallenge -> { /* then verify with MfaVerificationType.Oob(enrollment.oobCode!!, code) */ } - else -> { } -} -``` - -After enrolling an OTP factor, verify with `MfaVerificationType.Otp(code)` to receive credentials. - -## DPoP - -If the `AuthenticationAPIClient` was configured with `useDPoP(context)`, the MFA client inherits it. The DPoP proof is attached to the final `verify` call. - -## Errors - -All four exception types expose `getCode()`, `getDescription()`, `statusCode`, `getValue(key)`, `isNetworkError` and `cause`. Branch on the code, not the description: - -| Code | Meaning | -|------|---------| -| `invalid_token` | MFA token expired or invalid; restart login | -| `invalid_grant`, `invalid_oob_code`, `invalid_binding_code`, `expired_token` | Wrong or expired code | -| `enrollment_conflict` | Authenticator already enrolled | -| `unsupported_challenge_type` | Factor not enabled for the tenant | -| `authenticator_not_found` | Unknown authenticator id | - -## Common mistakes - -- Verifying an OOB factor (SMS, email, push) without calling `challenge` first. -- Calling `getAuthenticators` with an empty list. -- Forgetting `.setAudience` / `.setScope` on the original `login` request, then getting credentials for the wrong API. -- Using removed `AuthenticationAPIClient` MFA methods from v3. -- Typing the enroll callback as a concrete challenge class. +- `./gradlew assembleDebug` passes. +- No removed MFA method or hand-written `/oauth/token` request remains. +- Waiting on the developer: sign in with a user enrolled in the factor, complete + the challenge, and confirm the app receives credentials. diff --git a/skills/organizations/SKILL.md b/skills/organizations/SKILL.md deleted file mode 100644 index 23d37a00e..000000000 --- a/skills/organizations/SKILL.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -name: organizations -description: >- - Use when building a multi-tenant or B2B Auth0.Android app with Auth0 - Organizations: logging a user into a specific organization with - WebAuthProvider.withOrganization, accepting an organization invitation link with - withInvitationUrl and App Links, reading the org_id claim, or associating a - password reset with an organization. -metadata: - type: sub-skill - library: Auth0.Android - library_version: 4.3.1 -requires: - - auth0-android ---- - -# Auth0.Android - Organizations - -Organizations are available on Enterprise and Startup plans. Reference: [`examples/organizations.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/organizations.md). There is no dedicated organization accessor on `Credentials`. - -## Log in to an organization - -```kotlin -WebAuthProvider.login(account) - .withOrganization("org_abc123") // organization id (starts with org_) or name - .start(this, callback) -``` - -The SDK validates the ID token against the value you pass: an id starting with `org_` is compared to the `org_id` claim, anything else is compared (lowercased) to `org_name`. A mismatch fails the login with a token validation error. - -## Accept an invitation - -Invitation links are `https` only, so set up [Android App Links](https://auth0.com/docs/get-started/applications/enable-android-app-links-support) so the link opens your app, and set the application's Application Login URI in the Dashboard to that HTTPS URL so invitations point at it. In `onCreate` or `onNewIntent`, pass the full URL through as-is. The SDK extracts the `organization` and `invitation` parameters; do not parse them yourself. - -```kotlin -intent?.data?.takeIf { it.isHierarchical }?.let { uri -> // opaque URIs (mailto:) make the SDK throw - WebAuthProvider.login(account) - .withInvitationUrl(uri.toString()) - .start(this, callback) -} -``` - -If the URL lacks the expected values the callback receives an error. - -## Read the organization - -`org_id` and `org_name` are ID token claims. `credentials.user` decodes the ID token, so non-standard claims are in `getExtraInfo()`: - -```kotlin -val orgId = credentials.user.getExtraInfo()["org_id"] as? String -``` - -## Password reset for an organization user - -```kotlin -authentication.resetPassword("user@example.com", "Username-Password-Authentication", "org_abc123") - .start(voidCallback) -``` - -The third argument must be the organization id, not the name. Auth0 adds the organization details to the reset redirect URL and email templates. - -## Notes - -- Enable the organization and the connection on the Auth0 application, and set the application's organization behavior in the Dashboard. -- Keep the client ID and domain in `strings.xml`, read through `Auth0.getInstance(context)`. No client secret in the app. -- Store credentials with `SecureCredentialsManager`. -- Do not build the `/authorize` URL by hand to add `organization`; use the builder. diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md index ac0fb5b4e..7752cf2ff 100644 --- a/skills/passkeys/SKILL.md +++ b/skills/passkeys/SKILL.md @@ -1,111 +1,41 @@ --- -name: passkeys +name: auth0-android-passkeys description: >- - Use when adding passkeys to an Auth0.Android app: signing in with a passkey, - signing up a new user with a passkey, or enrolling a passkey for an already - signed-in user through the My Account API. Covers AuthenticationAPIClient - passkeyChallenge, signupWithPasskey, signinWithPasskey, MyAccountAPIClient, the - AndroidX Credential Manager ceremony, and identifier verification on signup. + Use when adding passkey sign-up, sign-in or enrollment to an Android app that + uses com.auth0.android:auth0. metadata: - type: sub-skill library: Auth0.Android library_version: 4.3.1 -requires: - - auth0-android --- -# Auth0.Android - Passkeys - -Reference: [`examples/passkeys.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/passkeys.md) and [`examples/my-account-api.md`](https://github.com/auth0/Auth0.Android/blob/main/examples/my-account-api.md). - -Requirements: a custom domain, the **Passkeys** grant enabled on the application, Android Device Settings configured for the application, and Android 9 (API 28) or higher for passkey calls. The Digital Asset Links file must be served and verified for the custom domain. - -Pattern: Auth0 challenge, then the AndroidX Credential Manager ceremony, then Auth0 sign-in or enroll with the credential. The SDK removed `PasskeyAuthProvider`, `PasskeyProvider` and `PasskeyManager` in v4. - -## Gradle - -Credential Manager is not a dependency of the SDK, and Gson is not exposed on your compile classpath. Add to the app module: - -```groovy -implementation 'androidx.credentials:credentials:1.3.0' -implementation 'androidx.credentials:credentials-play-services-auth:1.3.0' -implementation 'com.google.code.gson:gson:2.11.0' -``` - -`PublicKeyCredentials` is `com.auth0.android.request.PublicKeyCredentials`. - -## Sign in - -```kotlin -val authentication = AuthenticationAPIClient(account) - -val challenge = authentication.passkeyChallenge(realm = "Username-Password-Authentication").await() - -val option = GetPublicKeyCredentialOption(Gson().toJson(challenge.authParamsPublicKey)) -val result = credentialManager.getCredential(context, GetCredentialRequest(listOf(option))) -val response = (result.credential as PublicKeyCredential).authenticationResponseJson - -val credentials = authentication - .signinWithPasskey(challenge.authSession, Gson().fromJson(response, PublicKeyCredentials::class.java), "Username-Password-Authentication") - .validateClaims() - .setScope("openid profile email offline_access") - .await() -credentialsManager.saveCredentials(credentials) -``` - -`passkeyChallenge(realm: String? = null, organization: String? = null)`. `signinWithPasskey(authSession, authResponse, realm?, organization?, verification, verificationRequired)`; `authSession` is first. `authResponse` can be a `PublicKeyCredentials` or the raw JSON `String`. - -## Sign up - -```kotlin -val challenge = authentication - .signupWithPasskey(UserData(email = "user@example.com"), realm = "Username-Password-Authentication") - .await() - -val request = CreatePublicKeyCredentialRequest(Gson().toJson(challenge.authParamsPublicKey)) -val created = credentialManager.createCredential(context, request) as CreatePublicKeyCredentialResponse -val response = Gson().fromJson(created.registrationResponseJson, PublicKeyCredentials::class.java) - -val credentials = authentication - .signinWithPasskey(challenge.authSession, response, "Username-Password-Authentication") - .validateClaims() - .await() -``` - -`signupWithPasskey(userData: UserData, realm?, organization?, deliveryMethod?)`. `UserData` is `com.auth0.android.request.UserData`, not a Map. - -### Identifier verification - -If the connection requires verified email or phone, `challenge.verificationRequired` lists `PasskeyVerificationMethod` values. Collect the OTP codes before creating the platform credential, then pass `verification = codes` and `verificationRequired = challenge.verificationRequired.orEmpty()` to `signinWithPasskey`. On `error.isPasskeyVerificationRetryable`, re-collect the codes in `error.passkeyVerificationRequired` (it is null when the server omits them, so fall back to `challenge.verificationRequired`) and retry with the same credential and `error.passkeyAuthSession`, not the original `challenge.authSession`. If `error.isMultifactorRequired`, continue with the [mfa](../mfa/SKILL.md) skill instead of restarting. Any other error means restarting from `signupWithPasskey`. Optional `deliveryMethod`: `DeliveryMethod.TEXT` or `VOICE`. - -## Enroll a passkey for a signed-in user - -Uses the same create ceremony, but goes through `MyAccountAPIClient` with a My Account token. It does not create an account and returns no new `Credentials`. `awaitApiCredentials` exchanges the refresh token, so sign-in must request `offline_access`. If that refresh token was issued for another audience, Multi-Resource Refresh Token must be configured for the My Account API on the tenant. - -```kotlin -val api = credentialsManager.awaitApiCredentials( - audience = "https://YOUR_CUSTOM_DOMAIN/me/", - scope = "create:me:authentication_methods" -) - -val myAccount = MyAccountAPIClient(account, api.accessToken) -val challenge = myAccount.passkeyEnrollmentChallenge().await() - -val request = CreatePublicKeyCredentialRequest(Gson().toJson(challenge.authParamsPublicKey)) -val created = credentialManager.createCredential(context, request) as CreatePublicKeyCredentialResponse -val credential = Gson().fromJson(created.registrationResponseJson, PublicKeyCredentials::class.java) - -val method = myAccount.enroll(credential, challenge).await() // PasskeyAuthenticationMethod -``` - -`passkeyEnrollmentChallenge(userIdentity: String? = null, connection: String? = null)` throws `MyAccountException`. Pass `userIdentity` when the user logged in through a linked account. - -## Common mistakes - -- Omitting `.validateClaims()` on `signinWithPasskey`. -- Using the login access token for enrollment instead of one for the `/me/` audience with `create:me:authentication_methods`. -- Calling `signupWithPasskey` to add a passkey to an existing user; that creates a new account. -- Crossing `getCredential` (sign-in) and `createCredential` (signup, enroll). -- Passing the ceremony JSON as the credential without parsing it into `PublicKeyCredentials` (or using the `String` overload). -- Missing or unverified Digital Asset Links on the custom domain; Credential Manager refuses the ceremony. -- Expecting a dedicated MFA exception. If the tenant adds a second factor, `AuthenticationException.isMultifactorRequired` is true; continue with the [mfa](../mfa/SKILL.md) skill. +# Passkeys with Auth0.Android + +Follow [examples/passkeys.md](../../examples/passkeys.md) and +[examples/my-account-api.md](../../examples/my-account-api.md) for the code. +These are the places agents go wrong. + +## Gotchas + +- **The app adds the passkey dependencies itself.** The SDK doesn't depend on + `androidx.credentials`, and its Gson isn't exposed, so add + `androidx.credentials:credentials`, `androidx.credentials:credentials-play-services-auth` + and `com.google.code.gson:gson` to the app module. (`auth0/build.gradle`) +- **`signupWithPasskey` returns a challenge, not credentials.** The credentials + come from the later `signinWithPasskey` call, which needs `.validateClaims()`. + (`AuthenticationAPIClient.kt` `signupWithPasskey`) +- **Enrolling a passkey for a signed-in user needs a My Account API token.** + `MyAccountAPIClient(auth0, accessToken)` accepts any token, but the API needs + one issued for `https://{domain}/me/`. Get it with + `credentialsManager.getApiCredentials("https://{domain}/me/", ...)`, which + needs a refresh token, so login must request `offline_access`. + ([My Account API](https://auth0.com/docs/manage-users/my-account-api); + `CredentialsManager.kt` `getApiCredentials`) + +## Verify + +- `./gradlew assembleDebug` passes with the three dependencies in the app module. +- `signinWithPasskey` calls have `.validateClaims()`. +- `MyAccountAPIClient` gets its token from `getApiCredentials` with the + `/me/` audience, not from the login credentials. +- Waiting on the developer: on a device with a screen lock, create a passkey, + sign out, and sign back in with it. From 7b9a7bdfd16189bf62c8ed7cf092ee05c2a1a264 Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Thu, 3 Dec 2026 18:08:25 +0530 Subject: [PATCH 7/7] docs(skills): drop source-file citations from the Android skills Evals showed agents treating "(`WebAuthProvider.kt` ...)" as a cue to fetch and read the SDK source, which raised token use without changing the result. The hub now says the gotchas are already checked against the source. Co-Authored-By: Claude --- skills/SKILL.md | 14 +++++--------- skills/mfa/SKILL.md | 1 - skills/passkeys/SKILL.md | 6 ++---- 3 files changed, 7 insertions(+), 14 deletions(-) diff --git a/skills/SKILL.md b/skills/SKILL.md index c8990a947..a3fccb289 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -13,8 +13,9 @@ metadata: # Auth0.Android Follow [README.md](../README.md) and [examples/](../examples/) for setup and -code. This file lists only where the SDK surprises agents. Each item cites the -source at the version above. +code. This file lists only where the SDK surprises agents. Each item has been +checked against the SDK source at the version above, so don't read the source +to confirm it. ## Gotchas @@ -23,28 +24,23 @@ source at the version above. stored. Once the access token expires, `getCredentials` fails with `CredentialsManagerException.NO_REFRESH_TOKEN`. Pass the full scope, including `offline_access`, whenever the app keeps a session. - (`WebAuthProvider.kt` `withScope`; `CredentialsManagerException.kt`) - **Only Web Auth validates the ID token.** `AuthenticationAPIClient` requests skip validation unless you call `.validateClaims()`, and skipping it only logs an error. Call it on every request that returns `Credentials`. - (`BaseAuthenticationRequest.kt` `validateClaims`) - **Login and logout each default to the `https` scheme.** If the app uses a custom scheme, call `.withScheme()` on the logout builder too, not only on login. With `https`, the callback only reaches the app once Android App Links - are verified for it. (`WebAuthProvider.kt` `withScheme`) + are verified for it. - **`Credentials` has no claims map.** Read the user's claims from `credentials.user`; custom claims are in `credentials.user.getExtraInfo()`. - (`Credentials.kt` `user`; `UserProfile.kt` `getExtraInfo`) - **README's first snippet hardcodes the client ID and domain.** Put them in `strings.xml` and use `Auth0.getInstance(context)`, so they match the - `auth0Domain` manifest placeholder. (`README.md` "Alternatively") + `auth0Domain` manifest placeholder. - **`customTokenExchange(subjectTokenType, subjectToken)` takes the type first**, the reverse of `loginWithNativeSocialToken(token, tokenType)`. Both are strings, so a swap compiles and fails at runtime. - (`AuthenticationAPIClient.kt` `customTokenExchange`) - **Starting any Web Auth flow drops the one in progress.** A logout started while a login is pending cancels that login without a callback. - (`WebAuthProvider.kt` `resetManagerInstance`) For MFA, read [mfa/SKILL.md](mfa/SKILL.md). For passkeys, read [passkeys/SKILL.md](passkeys/SKILL.md). diff --git a/skills/mfa/SKILL.md b/skills/mfa/SKILL.md index f5107c9ce..a0eb5f0af 100644 --- a/skills/mfa/SKILL.md +++ b/skills/mfa/SKILL.md @@ -22,7 +22,6 @@ for the code. These are the places agents go wrong. requests. ([V4_MIGRATION_GUIDE.md](../../V4_MIGRATION_GUIDE.md)) - **`mfaClient(...).verify()` doesn't validate the ID token**, and it has no `validateClaims()`. Don't trust its ID token claims for access decisions. - (`MfaApiClient.kt` `verify`) - **The SDK doesn't wait for push approval.** It has no polling, so call `verify` again on an interval while `error.getCode()` is `authorization_pending`, and stop on success or any other error. diff --git a/skills/passkeys/SKILL.md b/skills/passkeys/SKILL.md index 7752cf2ff..83c4b7288 100644 --- a/skills/passkeys/SKILL.md +++ b/skills/passkeys/SKILL.md @@ -19,17 +19,15 @@ These are the places agents go wrong. - **The app adds the passkey dependencies itself.** The SDK doesn't depend on `androidx.credentials`, and its Gson isn't exposed, so add `androidx.credentials:credentials`, `androidx.credentials:credentials-play-services-auth` - and `com.google.code.gson:gson` to the app module. (`auth0/build.gradle`) + and `com.google.code.gson:gson` to the app module. - **`signupWithPasskey` returns a challenge, not credentials.** The credentials come from the later `signinWithPasskey` call, which needs `.validateClaims()`. - (`AuthenticationAPIClient.kt` `signupWithPasskey`) - **Enrolling a passkey for a signed-in user needs a My Account API token.** `MyAccountAPIClient(auth0, accessToken)` accepts any token, but the API needs one issued for `https://{domain}/me/`. Get it with `credentialsManager.getApiCredentials("https://{domain}/me/", ...)`, which needs a refresh token, so login must request `offline_access`. - ([My Account API](https://auth0.com/docs/manage-users/my-account-api); - `CredentialsManager.kt` `getApiCredentials`) + ([My Account API](https://auth0.com/docs/manage-users/my-account-api)) ## Verify