Skip to content
Merged
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
70 changes: 70 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
- [Get user information](#get-user-information)
- [Custom Token Exchange](#custom-token-exchange)
- [Native to Web SSO login](#native-to-web-sso-login)
- [Pushed Authorization Requests (PAR)](#pushed-authorization-requests-par)
- [DPoP](#dpop-1)
- [My Account API](#my-account-api)
- [Enroll a new passkey](#enroll-a-new-passkey)
Expand Down Expand Up @@ -1691,6 +1692,75 @@ authentication
```
</details>

### Pushed Authorization Requests (PAR)

This feature handles the browser authorization step of a [PAR (RFC 9126)](https://www.rfc-editor.org/rfc/rfc9126.html) flow. It opens the `/authorize` endpoint with a `request_uri` obtained from your backend's PAR endpoint call, and returns the authorization code for your backend to exchange for tokens.

> [!IMPORTANT]
> Auth0 only supports PAR for **confidential clients**. Since mobile apps are public clients, the `/oauth/par` and `/oauth/token` calls must be made by your backend (BFF - Backend for Frontend). The SDK only handles opening the browser with the `request_uri` and returning the resulting authorization code.
>
> Your Auth0 application configured in the SDK should use the **same client_id** as the one your backend uses when calling the `/oauth/par` endpoint.

```kotlin
WebAuthProvider.authorizeWithRequestUri(account)
.start(context, requestUri, object : Callback<AuthorizationCode, AuthenticationException> {
override fun onSuccess(result: AuthorizationCode) {
// Send result.code to your BFF for token exchange
// Validate result.state against the state your BFF used in the PAR request
}

override fun onFailure(exception: AuthenticationException) {
// Handle error
}
})
```

> [!NOTE]
> The SDK does not validate the `state` parameter. The `state` is generated by your BFF when calling `/oauth/par` and returned as-is in `AuthorizationCode.state`. Your app or BFF **must** validate that the returned `state` matches the original value to prevent CSRF attacks.

<details>
<summary>Using coroutines</summary>

```kotlin
try {
val authCode = WebAuthProvider.authorizeWithRequestUri(account)
.await(context, requestUri)
// Send authCode.code to your BFF for token exchange
// Validate authCode.state against the state your BFF used in the PAR request
} catch (e: AuthenticationException) {
e.printStackTrace()
}
```
</details>

<details>
<summary>Using Java</summary>

```java
WebAuthProvider.authorizeWithRequestUri(account)
.start(context, requestUri, new Callback<AuthorizationCode, AuthenticationException>() {
@Override
public void onSuccess(@NonNull AuthorizationCode result) {
// Send result.getCode() to your BFF for token exchange
// Validate result.getState() against the state your BFF used in the PAR request
}

@Override
public void onFailure(@NonNull AuthenticationException exception) {
// Handle error
}
});
```
</details>

You can also pass a session transfer token to enable web SSO by transferring an existing native session to the browser:

```kotlin
WebAuthProvider.authorizeWithRequestUri(account)
.withSessionTransferToken(sessionTransferToken)
.await(context, requestUri)
```

## DPoP

[DPoP](https://www.rfc-editor.org/rfc/rfc9449.html) (Demonstrating Proof of Possession) is an application-level mechanism for sender-constraining OAuth 2.0 access and refresh tokens by proving that the app is in possession of a certain private key. You can enable it by calling the `useDPoP(context: Context)` method. This ensures that DPoP proofs are generated for requests made through the AuthenticationAPI client.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.auth0.android.provider

import com.auth0.android.authentication.AuthenticationException

/**
* Parses the result from an authorization redirect callback.
*/
internal object AuthorizeResultParser {

sealed class CodeResult {
data class Success(val code: String, val state: String?) : CodeResult()
data class Error(val exception: AuthenticationException) : CodeResult()
object Canceled : CodeResult()
object Invalid : CodeResult()
}

private const val KEY_CODE = "code"
private const val KEY_STATE = "state"
private const val KEY_ERROR = "error"
private const val KEY_ERROR_DESCRIPTION = "error_description"

fun parse(result: AuthorizeResult, requestCode: Int): CodeResult {
if (!result.isValid(requestCode)) {
return CodeResult.Invalid
}

if (result.isCanceled) {
return CodeResult.Canceled
}

val values = CallbackHelper.getValuesFromUri(result.intentData)
if (values.isEmpty()) {
return CodeResult.Invalid
}

val error = values[KEY_ERROR]
if (error != null) {
val description = values[KEY_ERROR_DESCRIPTION] ?: error
return CodeResult.Error(AuthenticationException(error, description))
}

val code = values[KEY_CODE]
?: return CodeResult.Error(
AuthenticationException(
"access_denied",
"No authorization code was received in the callback."
)
)

return CodeResult.Success(code = code, state = values[KEY_STATE])
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package com.auth0.android.provider
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This manager doesn't survive Activity recreation. If the user rotates the device while the browser is open, managerInstance is lost and the callback silently fails.
OAuthManager handles this via toState() / onRestoreInstanceState(). PARCodeManager has no equivalent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added


import android.content.Context
import com.auth0.android.Auth0
import com.auth0.android.authentication.AuthenticationException
import com.auth0.android.callback.Callback
import com.auth0.android.result.AuthorizationCode

/**
* Manager for handling PAR (Pushed Authorization Request) code-only flows.
* This manager handles opening the authorize URL with a request_uri and
* returns the authorization code to the caller for BFF token exchange.
*/
internal class PARCodeManager(
private val account: Auth0,
private val callback: Callback<AuthorizationCode, AuthenticationException>,
private val requestUri: String,
private val sessionTransferToken: String? = null,
private val ctOptions: CustomTabsOptions = CustomTabsOptions.newBuilder().build()
) : ResumableManager() {

private var requestCode = 0

fun startAuthentication(context: Context, requestCode: Int) {
this.requestCode = requestCode
val additionalParams = buildMap {
sessionTransferToken?.let { put("session_transfer_token", it) }
}
val uri = PARUtils.buildAuthorizeUri(account, requestUri, additionalParams)
AuthenticationActivity.authenticateUsingBrowser(context, uri, false, ctOptions)
}

override fun resume(result: AuthorizeResult): Boolean {
Comment thread
utkrishtsahu marked this conversation as resolved.
return when (val parsed = AuthorizeResultParser.parse(result, requestCode)) {
is AuthorizeResultParser.CodeResult.Success -> {
callback.onSuccess(AuthorizationCode(parsed.code, parsed.state))
true
}
is AuthorizeResultParser.CodeResult.Error -> {
callback.onFailure(parsed.exception)
true
}
is AuthorizeResultParser.CodeResult.Canceled -> {
callback.onFailure(
AuthenticationException(
AuthenticationException.ERROR_VALUE_AUTHENTICATION_CANCELED,
"The user closed the browser app and the authentication was canceled."
)
)
true
}
AuthorizeResultParser.CodeResult.Invalid -> false
}
}

override fun failure(exception: AuthenticationException) {
callback.onFailure(exception)
}

internal fun toState(): PARCodeManagerState {
return PARCodeManagerState(
auth0 = account,
requestCode = requestCode,
requestUri = requestUri,
sessionTransferToken = sessionTransferToken,
ctOptions = ctOptions
)
}

internal companion object {
private val TAG = PARCodeManager::class.java.simpleName

fun fromState(
state: PARCodeManagerState,
callback: Callback<AuthorizationCode, AuthenticationException>
): PARCodeManager {
val manager = PARCodeManager(
account = state.auth0,
callback = callback,
requestUri = state.requestUri,
sessionTransferToken = state.sessionTransferToken,
ctOptions = state.ctOptions
)
manager.requestCode = state.requestCode
return manager
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.auth0.android.provider

import android.os.Parcel
import android.os.Parcelable
import android.util.Base64
import androidx.core.os.ParcelCompat
import com.auth0.android.Auth0
import com.auth0.android.request.internal.GsonProvider
import com.google.gson.Gson

internal data class PARCodeManagerState(
val auth0: Auth0,
val requestCode: Int,
val requestUri: String,
val sessionTransferToken: String?,
val ctOptions: CustomTabsOptions
) {

private class PARCodeManagerJson(
val auth0ClientId: String,
val auth0DomainUrl: String,
val auth0ConfigurationUrl: String?,
val requestCode: Int,
val requestUri: String,
val sessionTransferToken: String?,
val ctOptions: String
)

fun serializeToJson(gson: Gson = GsonProvider.gson): String {
val parcel = Parcel.obtain()
try {
parcel.writeParcelable(ctOptions, Parcelable.PARCELABLE_WRITE_RETURN_VALUE)
val ctOptionsEncoded = Base64.encodeToString(parcel.marshall(), Base64.DEFAULT)

val json = PARCodeManagerJson(
auth0ClientId = auth0.clientId,
auth0DomainUrl = auth0.domain,
auth0ConfigurationUrl = auth0.configurationDomain,
requestCode = requestCode,
requestUri = requestUri,
sessionTransferToken = sessionTransferToken,
ctOptions = ctOptionsEncoded
)
return gson.toJson(json)
} finally {
parcel.recycle()
}
}

companion object {
fun deserializeState(
json: String,
gson: Gson = GsonProvider.gson
): PARCodeManagerState {
val parcel = Parcel.obtain()
try {
val parsed = gson.fromJson(json, PARCodeManagerJson::class.java)

val decodedCtOptionsBytes = Base64.decode(parsed.ctOptions, Base64.DEFAULT)
parcel.unmarshall(decodedCtOptionsBytes, 0, decodedCtOptionsBytes.size)
parcel.setDataPosition(0)

val customTabsOptions = ParcelCompat.readParcelable(
parcel,
CustomTabsOptions::class.java.classLoader,
CustomTabsOptions::class.java
) ?: error("Couldn't deserialize CustomTabsOptions from Parcel")

val auth0 = Auth0.getInstance(
clientId = parsed.auth0ClientId,
domain = parsed.auth0DomainUrl,
configurationDomain = parsed.auth0ConfigurationUrl
)

return PARCodeManagerState(
auth0 = auth0,
requestCode = parsed.requestCode,
requestUri = parsed.requestUri,
sessionTransferToken = parsed.sessionTransferToken,
ctOptions = customTabsOptions
)
} finally {
parcel.recycle()
}
}
}
}
40 changes: 40 additions & 0 deletions auth0/src/main/java/com/auth0/android/provider/PARUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.auth0.android.provider

import android.net.Uri
import com.auth0.android.Auth0
import com.auth0.android.authentication.AuthenticationException
import androidx.core.net.toUri

/**
* Shared utilities for PAR (Pushed Authorization Request) flows.
*/
internal object PARUtils {

internal const val REQUEST_URI_PREFIX = "urn:ietf:params:oauth:request_uri:"

/**
* Validates that the request_uri conforms to the expected format.
* @return true if valid, false otherwise.
*/
fun isValidRequestUri(requestUri: String): Boolean {
return requestUri.startsWith(REQUEST_URI_PREFIX)
}

/**
* Builds a minimal /authorize URI for PAR flows containing only client_id and request_uri,
* plus any additional query parameters.
*/
fun buildAuthorizeUri(
account: Auth0,
requestUri: String,
additionalParameters: Map<String, String> = emptyMap()
): Uri {
val builder = account.authorizeUrl.toUri().buildUpon()
.appendQueryParameter("client_id", account.clientId)
.appendQueryParameter("request_uri", requestUri)
for ((key, value) in additionalParameters) {
builder.appendQueryParameter(key, value)
}
return builder.build()
}
}
Loading
Loading