Skip to content

Commit

Permalink
feature: Passkey support
Browse files Browse the repository at this point in the history
Support for passkeys for both Android and iOS have been added. To make this possible, numerous action has been taken on the codebase.

## SDK version has been pinned to 4.1.x
Previous releases did not pin the version on iOS, and android was using 4.0. If you experiencing differences with this update, please refer to the SDK changelogs:
https://curity.io/docs/haapi-android-sdk/latest/CHANGELOG.html
https://curity.io/docs/haapi-ios-sdk/latest/CHANGELOG.html

## Multiple new events
* RegistrationStep
* WebAuthnAuthenticationStep
* WebAuthnUserCancelled
* WebAuthnAuthenticationFailed
* WebAuthnRegistrationFailed
* WebAuthnRegistrationFailedKeyRegistered
* HaapiLoading
* HaapiFinishedLoading
* LoggedOut
* UnknownRespons
  • Loading branch information
daniellindau authored Nov 21, 2024
2 parents 3206ff5 + d983219 commit d93109b
Show file tree
Hide file tree
Showing 23 changed files with 1,208 additions and 1,363 deletions.
120 changes: 59 additions & 61 deletions README.md

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ def safeExtGet(prop, fallback) {
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.9.21"
implementation 'se.curity.identityserver:identityserver.haapi.android.sdk:4.0.0'
implementation 'com.google.code.gson:gson:2.10'
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.9.22"
implementation "se.curity.identityserver:identityserver.haapi.android.sdk:4.1.0"
implementation "com.google.code.gson:gson:2.10"
implementation "com.facebook.react:react-android:${safeExtGet('reactNativeVersion', '+')}"
implementation "androidx.credentials:credentials:1.2.2"
}


Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,22 @@ package io.curity.haapi.react

import android.util.Log
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableMap
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import se.curity.identityserver.haapi.android.sdk.HaapiAccessor
import se.curity.identityserver.haapi.android.sdk.HaapiAccessorFactory

class HaapiAccessorRepository(
conf: ReadableMap,
conf: Map<String, Any>,
reactContext: ReactApplicationContext
) {
private val _factory: HaapiAccessorFactory
private var backingAccessor: HaapiAccessor? = null

init {
val confMap = conf.toHashMap()
val haapiConfiguration = HaapiConfigurationUtil.createConfiguration(conf.toHashMap(), reactContext)
val haapiConfiguration = HaapiConfigurationUtil.createConfiguration(conf, reactContext)
val factory = HaapiAccessorFactory(haapiConfiguration)
HaapiConfigurationUtil.addFallbackConfiguration(factory, confMap, reactContext)
HaapiConfigurationUtil.addFallbackConfiguration(factory, conf, reactContext)
_factory = factory
backingAccessor = null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import javax.net.ssl.X509TrustManager

object HaapiConfigurationUtil {

fun createConfiguration(conf: HashMap<String, Any>, reactContext: ReactApplicationContext) = HaapiConfiguration(
fun createConfiguration(conf: Map<String, Any>, reactContext: ReactApplicationContext) = HaapiConfiguration(
keyStoreAlias = asStringOrDefault(
conf, "keyStoreAlias", "haapi-react-native-android"
),
Expand Down Expand Up @@ -74,7 +74,7 @@ object HaapiConfigurationUtil {
tokenBoundConfiguration = createTokenBoundConfiguration(reactContext)
)

fun addFallbackConfiguration(accessorFactory: HaapiAccessorFactory, conf: HashMap<String, Any>, context: Context) {
fun addFallbackConfiguration(accessorFactory: HaapiAccessorFactory, conf: Map<String, Any>, context: Context) {
val registrationEndpoint = asOptionalUri(conf, "registrationEndpointUri") ?: return
val fallbackTemplate = asStringOrThrow(conf, "fallback_template_id")
val registrationClientSecret = asStringOrThrow(conf, "registration_secret")
Expand All @@ -95,19 +95,19 @@ object HaapiConfigurationUtil {
currentTimeMillisProvider = { System.currentTimeMillis() }
)

private fun asStringMap(conf: HashMap<String, Any>, parameter: String): Map<String, String> {
private fun asStringMap(conf: Map<String, Any>, parameter: String): Map<String, String> {
return conf[parameter] as? Map<String, String> ?: mapOf()
}

private fun asStringOrDefault(conf: HashMap<String, Any>, parameter: String, defaultValue: String): String =
private fun asStringOrDefault(conf: Map<String, Any>, parameter: String, defaultValue: String): String =
asOptionalString(conf, parameter) ?: defaultValue

private fun asStringOrThrow(conf: HashMap<String, Any>, parameter: String): String =
private fun asStringOrThrow(conf: Map<String, Any>, parameter: String): String =
asOptionalString(conf, parameter) ?: throw RuntimeException("Missing $parameter in configuration")

private fun asOptionalString(conf: HashMap<String, Any>, parameter: String): String? = conf[parameter] as? String?
private fun asOptionalString(conf: Map<String, Any>, parameter: String): String? = conf[parameter] as? String?

private fun asOptionalUri(conf: HashMap<String, Any>, parameter: String): URI? {
private fun asOptionalUri(conf: Map<String, Any>, parameter: String): URI? {
val optionalValue = asOptionalString(conf, parameter)
return if (optionalValue != null) URI(optionalValue) else null
}
Expand Down
202 changes: 202 additions & 0 deletions android/src/main/java/io/curity/haapi/react/HaapiInteractionHandler.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/*
* Copyright 2024 Curity AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.curity.haapi.react

import android.util.Log
import com.facebook.react.bridge.ReactApplicationContext
import io.curity.haapi.react.events.EventEmitter
import io.curity.haapi.react.events.EventType
import io.curity.haapi.react.events.EventType.HaapiLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import se.curity.identityserver.haapi.android.sdk.HaapiManager
import se.curity.identityserver.haapi.android.sdk.OAuthTokenManager
import se.curity.identityserver.haapi.android.sdk.models.HaapiResponse
import se.curity.identityserver.haapi.android.sdk.models.Link
import se.curity.identityserver.haapi.android.sdk.models.OAuthAuthorizationResponseStep
import se.curity.identityserver.haapi.android.sdk.models.actions.FormActionModel
import se.curity.identityserver.haapi.android.sdk.models.oauth.TokenResponse
import kotlin.coroutines.CoroutineContext

class HaapiInteractionHandler(private val _reactContext: ReactApplicationContext) {

companion object {
private var _accessorRepository: HaapiAccessorRepository? = null
}

private val _haapiScope = CoroutineScope(Dispatchers.IO)
private val _eventEmitter = EventEmitter(_reactContext)


/**
* Load the configuration. This needs to be called before any interaction with HAAPI
* If called multiple times, the repo is closed to be able to load new configuration.
*
* @throws FailedToInitalizeHaapiException when the the configuration fails to load
*/
@Throws(FailedToInitalizeHaapiException::class)
fun loadConfiguration(conf: Map<String, Any>) {
// In case the app was recycled in dev mode, close the repo so we may set it up again
if (_accessorRepository != null) {
_accessorRepository!!.close()
}

try {
_accessorRepository = HaapiAccessorRepository(conf, _reactContext)
} catch (e: Exception) {
Log.w(TAG, "Failed to load configuration ${e.message}")
throw FailedToInitalizeHaapiException("Failed to load configuration", e)
}
}

/**
* Starts the flow by performing an authorization request to the configured server.
* This will perform attestation and obtain an API access token
*
* @throws FailedHaapiRequestException if the request fails
*/
@Throws(FailedHaapiRequestException::class)
fun startAuthentication(onSuccess: (HaapiResponse) -> Unit) {
withHaapiManager(onSuccess) { haapiManager, context ->
haapiManager.start(context)
}
}

@Throws(FailedHaapiRequestException::class)
fun followLink(link: Link, onSuccess: (HaapiResponse) -> Unit) {
withHaapiManager(onSuccess) { haapiManager, context ->
haapiManager.followLink(link, context)
}
}

@Throws(FailedHaapiRequestException::class)
fun submitForm(
form: FormActionModel,
parameters: Map<String, Any>, onSuccess: (HaapiResponse) -> Unit
) {
withHaapiManager(onSuccess) { haapiManager, context ->
haapiManager.submitForm(form, parameters, context)
}
}

@Throws(FailedTokenManagerRequestException::class)
fun exchangeCode(codeResponse: OAuthAuthorizationResponseStep, onSuccess: (TokenResponse) -> Unit) {
withTokenManager(onSuccess) { tokenManager, context ->
tokenManager.fetchAccessToken(codeResponse.properties.code, context)
}
}

@Throws(FailedTokenManagerRequestException::class)
fun refreshAccessToken(refreshToken: String, onSuccess: (TokenResponse) -> Unit) {
Log.d(TAG, "Refreshing access token")

try {
withTokenManager(onSuccess) { tokenManager, coroutineContext ->
tokenManager.refreshAccessToken(refreshToken, coroutineContext)
}
} catch (e: Exception) {
Log.d(TAG, "Failed to refresh tokens: ${e.message}")
throw FailedTokenManagerRequestException("Failed to refresh token", e)
}
}

fun logoutAndRevokeTokens(accessToken: String, refreshToken: String? = null) {
try {
if (refreshToken != null) {
Log.d(TAG, "Revoking refresh token")
withTokenManager { tokenManager, context ->
tokenManager.revokeRefreshToken(refreshToken!!, context)
null
}
} else {
Log.d(TAG, "Revoking access token")
withTokenManager { tokenManager, context ->
tokenManager.revokeAccessToken(accessToken, context)
null
}
}
} catch (e: Exception) {
Log.d(TAG, "Failed to revoke tokens: ${e.message}")
}

_accessorRepository?.close()
}

fun closeHaapiConnection() {
_accessorRepository?.close()
}

@Throws(FailedHaapiRequestException::class)
private fun withHaapiManager(
onSuccess: (HaapiResponse) -> Unit,
accessorRequest: suspend (manager: HaapiManager, context: CoroutineContext) -> HaapiResponse
) {
_eventEmitter.sendEvent(HaapiLoading)

val manager = _accessorRepository?.accessor?.haapiManager ?: throw notInitialized()

_haapiScope.launch {
try {
val response = accessorRequest(manager, this.coroutineContext)
onSuccess(response)
} catch (e: Exception) {
Log.w(TAG, "Failed to make HAAPI request: ${e.message}")
_eventEmitter.sendEvent(EventType.HaapiFinishedLoading)
throw FailedHaapiRequestException("Failed to make HAAPI request: ${e.message}", e)
}

_eventEmitter.sendEvent(EventType.HaapiFinishedLoading)
}
}

@Throws(FailedTokenManagerRequestException::class)
private fun withTokenManager(
onSuccess: ((TokenResponse) -> Unit)? = null,
accessorRequest: suspend (tokenManager: OAuthTokenManager, coroutineContext: CoroutineContext) -> TokenResponse?
) {
_eventEmitter.sendEvent(HaapiLoading)

val manager = _accessorRepository?.accessor?.oAuthTokenManager ?: throw notInitialized()

_haapiScope.launch {
try {
val response = accessorRequest(manager, this.coroutineContext)
if (onSuccess != null && response != null) {
onSuccess(response)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to make token request: ${e.message}")
_eventEmitter.sendEvent(EventType.HaapiFinishedLoading)
throw FailedTokenManagerRequestException("Failed to make token request", e)
}

_eventEmitter.sendEvent(EventType.HaapiFinishedLoading)
}

}

private fun notInitialized(): HaapiNotInitializedException {
Log.w(
TAG, "Accessor repository not initialized. " +
"Please run load() with configuration before accessing HAAPI functionality"
)
_eventEmitter.sendEvent(EventType.HaapiFinishedLoading)

throw HaapiNotInitializedException()
}
}
Loading

0 comments on commit d93109b

Please sign in to comment.