Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Each topic lives in its own file under [`examples/`](examples).

- [Email OTP — first-factor & MFA second-factor](examples/embedded-auth/authorize.md)
- [Username & Password — first-factor](examples/embedded-auth/password-authorize.md)
- [Passkey — first-factor](examples/embedded-auth/passkey.md)
- [Phone OTP (SMS/Voice) — first-factor & MFA second-factor](examples/embedded-auth/phone-authorize.md)
- [Push Notification Polling (OOB)](examples/embedded-auth/push-oob-polling.md)
- [Recovery Code](examples/embedded-auth/recovery-code.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import com.auth0.android.embedded.authorize.PhoneDeliveryMethod
import com.auth0.android.embedded.authorize.StepRequest
import com.auth0.android.embedded.authorize.authorizeCodeAdapter
import com.auth0.android.embedded.authorize.embeddedAuthErrorAdapter
import com.auth0.android.embedded.passkey.InvalidPasskeyResponseException
import com.auth0.android.embedded.passkey.passkeyAuthnResponse
import com.auth0.android.request.Request
import com.auth0.android.request.internal.GsonAdapter
import com.auth0.android.request.internal.GsonProvider
Expand Down Expand Up @@ -58,7 +60,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) {
* @param scope space-separated scopes to request. Must include `openid` for the terminal token
* exchange to return an ID token; defaults to `"openid profile email offline_access"`.
* @param audience optional API audience to request an access token for.
* @param capabilities the set of steps this client can handle in the flow.
* @param capabilities the set of steps this client can handle in the flow. Defaults to every step the
* SDK models.
*/
@JvmOverloads
public fun authorize(
Expand Down Expand Up @@ -145,6 +148,38 @@ public class EmbeddedAuthClient(private val auth0: Auth0) {
addParameter(PASSWORD_KEY, password)
}

/**
* Signs the user in with a passkey. Completes the flow when no further factor is required.
*
* Call it with the `authenticationResponseJson` of the credential the platform returned after
* running the ceremony for [NextAction.VerifyPasskey.requestJson]. Only the fields the server
* accepts are sent. The passkey must be discoverable, so the response must carry a `userHandle`.
*
* On success, it yields the [Credentials]. If the passkey is rejected, the request completes through
* [EmbeddedAuthException] with [EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY]
* and a new [NextAction.VerifyPasskey] that carries a fresh challenge. If the server requires further
* steps, [EmbeddedAuthError.InsufficientAuthorization.nextActions] carry them.
*
* A response that doesn't match the server's schema completes with [EmbeddedAuthError.InvalidInput]
* without sending a request; the flow is unchanged.
*/
public fun verifyPasskey(authenticationResponseJson: String): Request<Credentials, EmbeddedAuthException> {
val authnResponse = try {
passkeyAuthnResponse(authenticationResponseJson)
} catch (e: InvalidPasskeyResponseException) {
return FailedRequest(
EmbeddedAuthException(
INVALID_INPUT_ERROR,
e.message ?: DEFAULT_INVALID_INPUT_DESCRIPTION,
error = EmbeddedAuthError.InvalidInput
)
)
}
return terminalStep(EmbeddedCapability.VERIFY_PASSKEY) {
addParameter(AUTHN_RESPONSE_KEY, authnResponse)
}
}

/**
* Continues the flow by requesting a phone challenge for the authenticator at [index].
*
Expand Down Expand Up @@ -367,6 +402,7 @@ public class EmbeddedAuthClient(private val auth0: Auth0) {
private const val PHONE_KEY = "phone"
private const val USERNAME_KEY = "username"
private const val PASSWORD_KEY = "password"
private const val AUTHN_RESPONSE_KEY = "authn_response"
private const val DELIVERY_METHOD_KEY = "delivery_method"
private const val OTP_KEY = "otp"
private const val INDEX_KEY = "index"
Expand All @@ -375,6 +411,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) {
private const val CODE_KEY = "code"
private const val GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code"
private const val NO_ACTIVE_SESSION_ERROR = "no_active_session"
private const val INVALID_INPUT_ERROR = "invalid_input"
private const val DEFAULT_INVALID_INPUT_DESCRIPTION = "The input was rejected."

private const val DEFAULT_SCOPE = "openid profile email offline_access"

Expand All @@ -391,7 +429,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) {
EmbeddedCapability.VERIFY_RECOVERY_CODE,
EmbeddedCapability.CONFIRM_RECOVERY_CODE,
EmbeddedCapability.SIGNUP,
EmbeddedCapability.CONFIRM_SIGNUP
EmbeddedCapability.CONFIRM_SIGNUP,
EmbeddedCapability.VERIFY_PASSKEY
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ public sealed interface EmbeddedAuthError {
/** The username or the password was invalid; the server does not say which. */
INVALID_IDENTIFIER_OR_PASSWORD,

/** The submitted passkey was rejected. The new [NextAction.VerifyPasskey] carries a fresh challenge. */
INVALID_PASSKEY,

/** Authorization is pending (e.g., push notification awaiting user approval). Retry after a delay. */
AUTHORIZATION_PENDING,

Expand Down Expand Up @@ -97,6 +100,12 @@ public sealed interface EmbeddedAuthError {
*/
public data object Network : EmbeddedAuthError

/**
* Client-side guard: the input was rejected before any request was sent, so the flow is unchanged.
* Read [EmbeddedAuthException.description] for which field was rejected, and retry the step.
*/
public data object InvalidInput : EmbeddedAuthError

/** Client-side guard: no flow is in progress. Call [EmbeddedAuthClient.authorize] first. */
public data object NoActiveSession : EmbeddedAuthError

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.auth0.android.request.internal.GsonAdapter.Companion.forMap
import com.auth0.android.request.internal.GsonProvider
import com.auth0.android.request.internal.ResponseUtils.isNetworkError
import com.google.gson.Gson
import com.google.gson.ToNumberPolicy
import java.io.IOException
import java.io.Reader

Expand All @@ -32,6 +33,7 @@ private const val IP_BLOCKED = "ip_blocked"
private const val INVALID_CODE = "invalid_code"
private const val INVALID_IDENTIFIER_OR_CODE = "invalid_identifier_or_code"
private const val INVALID_IDENTIFIER_OR_PASSWORD = "invalid_identifier_or_password"
private const val INVALID_PASSKEY = "invalid_passkey"
private const val INVALID_GRANT = "invalid_grant"
private const val INVALID_REQUEST = "invalid_request"
private const val TOO_MANY_REQUESTS_STATUS = 429
Expand All @@ -51,7 +53,9 @@ internal fun authorizeCodeAdapter(gson: Gson): JsonAdapter<AuthorizeCode> =
* Translates every embedded-authentication error response into an [EmbeddedAuthException].
*/
internal fun embeddedAuthErrorAdapter(): ErrorAdapter<EmbeddedAuthException> {
val mapAdapter = forMap(GsonProvider.gson)
val mapAdapter = forMap(
GsonProvider.gson.newBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create()
)
return object : ErrorAdapter<EmbeddedAuthException> {

override fun fromRawResponse(
Expand Down Expand Up @@ -136,6 +140,7 @@ internal fun embeddedAuthErrorAdapter(): ErrorAdapter<EmbeddedAuthException> {
EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_CODE
INVALID_IDENTIFIER_OR_PASSWORD ->
EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_PASSWORD
INVALID_PASSKEY -> EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY
AUTHORIZATION_PENDING ->
EmbeddedAuthError.InsufficientAuthorization.Reason.AUTHORIZATION_PENDING
SLOW_DOWN -> EmbeddedAuthError.InsufficientAuthorization.Reason.SLOW_DOWN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public enum class EmbeddedCapability(public val value: String) {
CHALLENGE_PUSH("action:challenge:push:v1"),
VERIFY_OTP("action:verify:otp:v1"),
VERIFY_PASSWORD("action:verify:password:v1"),
VERIFY_PASSKEY("action:verify:passkey:v1"),
VERIFY_OOB("action:verify:oob:v1"),
VERIFY_RECOVERY_CODE("action:verify:recovery-code:v1"),
CONFIRM_RECOVERY_CODE("action:confirm:recovery-code:v1"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.auth0.android.embedded.authorize

import com.auth0.android.embedded.EmbeddedAuthClient
import com.auth0.android.embedded.EmbeddedAuthException
import com.auth0.android.embedded.passkey.PasskeyRequestOptions

/** One way to continue the embedded authentication flow, as reported on [EmbeddedAuthException.nextActions]. */
public sealed interface NextAction {
Expand All @@ -28,6 +29,25 @@ public sealed interface NextAction {
override val capability: EmbeddedCapability = EmbeddedCapability.VERIFY_PASSWORD
}

/**
* Continue by signing in with a passkey. Run the platform's passkey ceremony with [requestJson], then
* submit the result with [EmbeddedAuthClient.verifyPasskey].
*
* [options] exposes the main WebAuthn options. [requestJson] is the complete options object the
* server sent, ready to use as the request JSON of a Credential Manager `GetPublicKeyCredentialOption`.
* The challenge is single-use: after a failed attempt the server offers a new [VerifyPasskey] with a
* fresh one.
*/
@ConsistentCopyVisibility
public data class VerifyPasskey internal constructor(
public val options: PasskeyRequestOptions,
public val requestJson: String
) : NextAction {
override val capability: EmbeddedCapability = EmbeddedCapability.VERIFY_PASSKEY

override fun toString(): String = "VerifyPasskey(options=$options)"
}

/** Continue by requesting an email challenge. Act on it with [EmbeddedAuthClient.challengeEmail]. */
@ConsistentCopyVisibility
public data class ChallengeEmail internal constructor(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.auth0.android.embedded.authorize

import android.util.Log
import com.auth0.android.embedded.passkey.PasskeyRequestOptions
import com.auth0.android.embedded.passkey.UserVerification
import com.auth0.android.request.internal.GsonProvider

private const val TAG = "NextActionMapper"

Expand All @@ -16,6 +19,13 @@ private const val IDENTIFIERS_KEY = "identifiers"
private const val EMAIL_KEY = "email"
private const val PHONE_NUMBER_KEY = "phone_number"
private const val REQUIRED_KEY = "required"
private const val AUTHN_PARAMS_PUBLIC_KEY_KEY = "authn_params_public_key"
private const val CHALLENGE_KEY = "challenge"
private const val TIMEOUT_KEY = "timeout"
private const val RP_ID_KEY = "rpId"
private const val USER_VERIFICATION_KEY = "userVerification"
private const val HINTS_KEY = "hints"
private const val ALLOW_CREDENTIALS_KEY = "allowCredentials"

internal fun List<Map<String, Any>>.toNextActions(): List<NextAction> = mapNotNull { it.toNextAction() }

Expand All @@ -26,6 +36,27 @@ private fun Map<String, Any>.toNextAction(): NextAction? {
EmbeddedCapability.IDENTIFY_PHONE -> NextAction.IdentifyPhone
EmbeddedCapability.IDENTIFY_USERNAME -> NextAction.IdentifyUsername
EmbeddedCapability.VERIFY_PASSWORD -> NextAction.VerifyPassword
EmbeddedCapability.VERIFY_PASSKEY -> {
val params = this[AUTHN_PARAMS_PUBLIC_KEY_KEY] as? Map<*, *>
?: return dropped(raw, AUTHN_PARAMS_PUBLIC_KEY_KEY)
val challenge = params[CHALLENGE_KEY] as? String
?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$CHALLENGE_KEY")
val timeout = params[TIMEOUT_KEY] as? Long
?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$TIMEOUT_KEY")
val rpId = params[RP_ID_KEY] as? String
?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$RP_ID_KEY")
val userVerification = UserVerification.fromValue(params[USER_VERIFICATION_KEY] as? String)
?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$USER_VERIFICATION_KEY")
val hints = (params[HINTS_KEY] as? List<*>)?.filterIsInstance<String>().orEmpty()
val allowCredentials = (params[ALLOW_CREDENTIALS_KEY] as? List<*>)
?.filterIsInstance<Map<*, *>>()
?.map { it.toStringKeyedMap() }
.orEmpty()
NextAction.VerifyPasskey(
options = PasskeyRequestOptions(challenge, timeout, rpId, userVerification, hints, allowCredentials),
requestJson = GsonProvider.gson.toJson(params)
)
}
EmbeddedCapability.CHALLENGE_EMAIL -> {
val index = (this[INDEX_KEY] as? Number)?.toInt() ?: return dropped(raw, INDEX_KEY)
val identifier = this[IDENTIFIER_KEY] as? String ?: return dropped(raw, IDENTIFIER_KEY)
Expand Down Expand Up @@ -95,6 +126,9 @@ private val SIGNUP_IDENTIFIER_TYPES: List<Pair<String, IdentifierType>> = listOf
PHONE_NUMBER_KEY to IdentifierType.PHONE
)

private fun Map<*, *>.toStringKeyedMap(): Map<String, Any> =
entries.mapNotNull { (key, value) -> if (key is String && value != null) key to value else null }.toMap()

/**
* Logs and drops a recognized next action whose required [field] the server omitted or sent
* malformed. Returns `null` so the entry is filtered out by [toNextActions].
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.auth0.android.embedded.passkey

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.google.gson.JsonParser

private const val ID_KEY = "id"
private const val RAW_ID_KEY = "rawId"
private const val TYPE_KEY = "type"
private const val RESPONSE_KEY = "response"
private const val CLIENT_DATA_JSON_KEY = "clientDataJSON"
private const val AUTHENTICATOR_DATA_KEY = "authenticatorData"
private const val SIGNATURE_KEY = "signature"
private const val USER_HANDLE_KEY = "userHandle"
private const val AUTHENTICATOR_ATTACHMENT_KEY = "authenticatorAttachment"
private const val CLIENT_EXTENSION_RESULTS_KEY = "clientExtensionResults"

private const val PUBLIC_KEY_TYPE = "public-key"
private const val MAX_CREDENTIAL_ID_LENGTH = 1364
private const val MAX_CLIENT_DATA_JSON_LENGTH = 1000
private const val MAX_AUTHENTICATOR_DATA_LENGTH = 750
private const val MAX_SIGNATURE_LENGTH = 750
private const val MAX_USER_HANDLE_LENGTH = 100

private val AUTHENTICATOR_ATTACHMENTS = setOf("platform", "cross-platform")

/** The assertion was rejected locally; the message names the field and never includes its value. */
internal class InvalidPasskeyResponseException(message: String) : IllegalArgumentException(message)

/**
* Builds the `authn_response` object from the `authenticationResponseJson` the platform returns,
* keeping only the fields `/e/authorize` accepts and enforcing its required fields, `type` value and
* length limits. `authenticatorAttachment` is kept only when it is a known value;
* `clientExtensionResults` is forwarded unchanged when it is an object.
*
* @throws InvalidPasskeyResponseException if the assertion doesn't satisfy the schema.
*/
internal fun passkeyAuthnResponse(authenticationResponseJson: String): Map<String, Any> {
val root = try {
JsonParser.parseString(authenticationResponseJson)
} catch (e: JsonParseException) {
throw InvalidPasskeyResponseException("The passkey response is not valid JSON.")
}
val assertion = root as? JsonObject
?: throw InvalidPasskeyResponseException("The passkey response must be a JSON object.")
val response = (assertion.get(RESPONSE_KEY) as? JsonObject)
?: throw InvalidPasskeyResponseException("The passkey response is missing \"$RESPONSE_KEY\".")

val type = assertion.requiredString(TYPE_KEY, PUBLIC_KEY_TYPE.length)
if (type != PUBLIC_KEY_TYPE) {
throw InvalidPasskeyResponseException("The passkey response \"$TYPE_KEY\" must be \"$PUBLIC_KEY_TYPE\".")
}

return buildMap {
put(ID_KEY, assertion.requiredString(ID_KEY, MAX_CREDENTIAL_ID_LENGTH))
put(RAW_ID_KEY, assertion.requiredString(RAW_ID_KEY, MAX_CREDENTIAL_ID_LENGTH))
put(TYPE_KEY, type)
put(
RESPONSE_KEY,
mapOf(
CLIENT_DATA_JSON_KEY to response.requiredString(CLIENT_DATA_JSON_KEY, MAX_CLIENT_DATA_JSON_LENGTH, "$RESPONSE_KEY."),
AUTHENTICATOR_DATA_KEY to response.requiredString(AUTHENTICATOR_DATA_KEY, MAX_AUTHENTICATOR_DATA_LENGTH, "$RESPONSE_KEY."),
SIGNATURE_KEY to response.requiredString(SIGNATURE_KEY, MAX_SIGNATURE_LENGTH, "$RESPONSE_KEY."),
USER_HANDLE_KEY to response.requiredString(USER_HANDLE_KEY, MAX_USER_HANDLE_LENGTH, "$RESPONSE_KEY.")
)
)
assertion.stringOrNull(AUTHENTICATOR_ATTACHMENT_KEY)
?.takeIf { it in AUTHENTICATOR_ATTACHMENTS }
?.let { put(AUTHENTICATOR_ATTACHMENT_KEY, it) }
(assertion.get(CLIENT_EXTENSION_RESULTS_KEY) as? JsonObject)
?.let { put(CLIENT_EXTENSION_RESULTS_KEY, it) }
}
}

private fun JsonObject.requiredString(key: String, maxLength: Int, path: String = ""): String {
val value = stringOrNull(key)
if (value.isNullOrEmpty()) {
throw InvalidPasskeyResponseException("The passkey response is missing \"$path$key\".")
}
if (value.length > maxLength) {
throw InvalidPasskeyResponseException("The passkey response \"$path$key\" is longer than $maxLength characters.")
}
return value
}

private fun JsonObject.stringOrNull(key: String): String? {
val element: JsonElement = get(key) ?: return null
return if (element.isJsonPrimitive && element.asJsonPrimitive.isString) element.asString else null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.auth0.android.embedded.passkey

/**
* The options the server offers for a passkey sign-in, as sent on [NextAction.VerifyPasskey].
*/
@ConsistentCopyVisibility
public data class PasskeyRequestOptions internal constructor(
/** The single-use, base64url-encoded challenge the authenticator signs. */
public val challenge: String,

/** How long, in milliseconds, the ceremony may take. */
public val timeout: Long,

/** The relying party identifier the passkey is scoped to. */
public val rpId: String,

/** Whether the authenticator must verify the user. */
public val userVerification: UserVerification,

/** Hints about which kind of authenticator to prefer, in order. Empty when the server sent none. */
public val hints: List<String>,

/**
* The credentials the server restricts the ceremony to, each as the server sent it. Empty when the
* server sent none. The API doesn't define an entry's fields, so they are not modelled here.
*/
public val allowCredentials: List<Map<String, Any>>
) {

override fun toString(): String =
"PasskeyRequestOptions(challenge='xxxxx', timeout=$timeout, rpId='$rpId', " +
"userVerification=$userVerification, hints=$hints, allowCredentials=${allowCredentials.size} entries)"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.auth0.android.embedded.passkey

/** How strongly the authenticator must verify the user during a passkey ceremony. */
public enum class UserVerification(internal val value: String) {
/** The ceremony fails unless the authenticator verifies the user. */
REQUIRED("required"),

/** The authenticator verifies the user when it can. */
PREFERRED("preferred"),

/** The authenticator should not verify the user. */
DISCOURAGED("discouraged");

internal companion object {
fun fromValue(value: String?): UserVerification? = entries.firstOrNull { it.value == value }
}
}
Loading
Loading