Skip to content

Commit

Permalink
Merge pull request #202 from okta/dt_cookie
Browse files Browse the repository at this point in the history
Add DT cookie and fix IDX for org auth servers
  • Loading branch information
rajdeepnanua-okta authored Jun 13, 2024
2 parents 1f2c8db + 329c46c commit 94a9e23
Show file tree
Hide file tree
Showing 11 changed files with 368 additions and 5 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,11 @@ The `InteractionCodeFlow` class is used to define and initiate an authentication

This class makes heavy use of [Kotlin Coroutines][kotlin-coroutines] to perform the actions asynchronously.

#### OidcClient.createInteractionCodeFlow
The `createInteractionCodeFlow` extension method on `OidcClient` is used to create an `InteractionCodeFlow`, and to start an authorization flow.
#### Constructing InteractionCodeFlow
`InteractionCodeFlow` can be instantiated with `OAuth2Client.default` by using the default constructor `InteractionCodeFlow()`. Alternatively, a non-default `OAuth2Client` or `OidcConfiguration` can be provided.

#### InteractionCodeFlow.start
The `start` method starts the authentication flow, and returns the result as `OAuth2ClientResult<Unit>`. The result is empty on success, and an error in form `OAuth2ClientResult.Error` in case of an error.

#### InteractionCodeFlow.resume
The `resume` method on an `InteractionCodeFlow` is used to reveal the current remediations.
Expand Down
5 changes: 5 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[versions]
authFoundation = "2.0.1"
androidxConstraintlayout = "2.1.4"
androidxDatastorePreferences = "1.1.1"
androidxTest = "1.5.0"
androidxTestRunner = "1.5.2"
androidxTestExt = "1.1.5"
Expand Down Expand Up @@ -32,12 +33,14 @@ okhttp = "4.12.0"
okio = "3.9.0"
oktaManagement = "14.0.0"
robolectric = "4.12.2"
securityCrypto = "1.0.0"
spotless = "6.7.0"
timber = "5.0.1"
truth = "1.1.5"

[libraries]
androidx-constraintlayout = { module = "androidx.constraintlayout:constraintlayout", version.ref = "androidxConstraintlayout" }
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidxDatastorePreferences" }

androidx-test-core = { module = "androidx.test:core", version.ref = "androidxTest" }
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExt" }
Expand Down Expand Up @@ -112,6 +115,8 @@ okta-management-sdk = { module = "com.okta.sdk:okta-sdk-impl", version.ref = "ok

robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }

security-crypto = { module = "androidx.security:security-crypto", version.ref = "securityCrypto" }

spotless = { module = "com.diffplug.spotless:spotless-plugin-gradle", version.ref = "spotless" }

timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" }
Expand Down
15 changes: 15 additions & 0 deletions okta-idx-kotlin/api/okta-idx-kotlin.api
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
public final class com/okta/authfoundation/client/DeviceTokenProvider {
public static final field Companion Lcom/okta/authfoundation/client/DeviceTokenProvider$Companion;
public static final field PREFERENCE_NAME Ljava/lang/String;
public fun <init> ()V
public fun <init> (Lcom/okta/authfoundation/util/AesEncryptionHandler;)V
public synthetic fun <init> (Lcom/okta/authfoundation/util/AesEncryptionHandler;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun getDeviceToken (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}

public final class com/okta/authfoundation/client/DeviceTokenProvider$Companion {
public final fun getInstance ()Lcom/okta/authfoundation/client/DeviceTokenProvider;
public final fun getPREFERENCE_KEY ()Landroidx/datastore/preferences/core/Preferences$Key;
}

public abstract class com/okta/idx/kotlin/client/IdxRedirectResult {
}

Expand All @@ -21,6 +35,7 @@ public final class com/okta/idx/kotlin/client/InteractionCodeFlow {
public fun <init> (Lcom/okta/authfoundation/client/OidcConfiguration;)V
public final fun evaluateRedirectUri (Landroid/net/Uri;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun exchangeInteractionCodeForTokens (Lcom/okta/idx/kotlin/dto/IdxRemediation;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun getClient ()Lcom/okta/authfoundation/client/OAuth2Client;
public final fun proceed (Lcom/okta/idx/kotlin/dto/IdxRemediation;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun resume (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun start (Landroid/net/Uri;Ljava/util/Map;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
Expand Down
4 changes: 4 additions & 0 deletions okta-idx-kotlin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@ dependencies {
api libs.coroutines.android
api libs.okta.auth.foundation

implementation libs.androidx.datastore.preferences
implementation libs.kotlin.serialization.json
implementation libs.okio.jvm
implementation libs.security.crypto

testImplementation libs.androidx.test.ext.junit
testImplementation libs.coroutines.test
testImplementation libs.junit
testImplementation libs.okhttp.mock.web.server
testImplementation libs.okhttp.tls
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2024-Present Okta, Inc.
*
* 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 com.okta.idx.kotlin.client

import com.okta.authfoundation.AuthFoundationDefaults
import com.okta.authfoundation.client.DeviceTokenProvider
import kotlinx.coroutines.runBlocking
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import kotlin.time.Duration.Companion.seconds

internal class DeviceTokenCookieJar : CookieJar {
private val savedCookiesCache = mutableMapOf<String, List<Cookie>>()
private val oidcClock by lazy { AuthFoundationDefaults.clock }

private val deviceTokenCookieBuilder: Cookie.Builder
get() {
val deviceToken = runBlocking { DeviceTokenProvider.instance.getDeviceToken() }
return getDtCookieBuilderWith(deviceToken)
}

private fun getDtCookieBuilderWith(deviceToken: String): Cookie.Builder {
return Cookie.Builder()
.name("DT")
.value(deviceToken)
.secure()
}

override fun loadForRequest(url: HttpUrl): List<Cookie> {
val deviceTokenCookie = deviceTokenCookieBuilder.domain(url.host).build()
val savedCookiesForDomain = savedCookiesCache[url.host]?.filter {
it.expiresAt > oidcClock.currentTimeEpochSecond().seconds.inWholeMilliseconds
} ?: emptyList()
val deviceTokenCookieList = listOf(deviceTokenCookie)
return savedCookiesForDomain + deviceTokenCookieList
}

override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
savedCookiesCache[url.host] = cookies
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2024-Present Okta, Inc.
*
* 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 com.okta.authfoundation.client

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.okta.authfoundation.InternalAuthFoundationApi
import com.okta.authfoundation.util.AesEncryptionHandler
import com.okta.idx.kotlin.client.LegacyDeviceTokenProvider
import kotlinx.coroutines.flow.firstOrNull
import java.util.UUID

@InternalAuthFoundationApi
class DeviceTokenProvider(
private val aesEncryptionHandler: AesEncryptionHandler = AesEncryptionHandler()
) {
companion object {
const val PREFERENCE_NAME = "com.okta.idx.client.deviceToken"
val PREFERENCE_KEY = stringPreferencesKey("encryptedDeviceToken")
val instance by lazy { DeviceTokenProvider() }
}

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(PREFERENCE_NAME)
private val context by lazy { ApplicationContextHolder.appContext }

suspend fun getDeviceToken(): String {
val encryptedDeviceToken = context.dataStore.data.firstOrNull()?.get(PREFERENCE_KEY)
return encryptedDeviceToken?.let {
aesEncryptionHandler.decryptString(it)
} ?: run {
val deviceToken = getLegacyDeviceToken() ?: createNewDeviceToken()
setDeviceToken(deviceToken)
deviceToken
}
}

private fun getLegacyDeviceToken(): String? {
return try {
val legacyDeviceTokenProvider = LegacyDeviceTokenProvider(context)
if (legacyDeviceTokenProvider.containsDeviceToken()) {
legacyDeviceTokenProvider.deviceToken
} else null
} catch (e: Exception) {
null
}
}

private fun createNewDeviceToken(): String =
UUID.randomUUID().toString().filter { it.isLetterOrDigit() }

private suspend fun setDeviceToken(deviceToken: String) =
context.dataStore.edit { preferences ->
preferences[PREFERENCE_KEY] = aesEncryptionHandler.encryptString(deviceToken)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ import com.okta.idx.kotlin.dto.v1.Response as V1Response
/**
* The InteractionCodeFlow class is used to define and initiate an authentication workflow utilizing the Okta Identity Engine.
*/
class InteractionCodeFlow constructor(private val client: OAuth2Client) {
class InteractionCodeFlow(val client: OAuth2Client) {
companion object {
init {
SdkVersionsRegistry.register(SDK_VERSION)
AuthFoundationDefaults.cookieJar = DeviceTokenCookieJar()
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2024-Present Okta, Inc.
*
* 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 com.okta.idx.kotlin.client

import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.VisibleForTesting
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import java.util.UUID

internal class LegacyDeviceTokenProvider(private val appContext: Context) {
internal companion object {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal const val FILE_NAME = "com.okta.authfoundation.device_token_storage"
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal const val PREFERENCE_KEY = "com.okta.authfoundation.device_token_key"
}

private val masterKeyAlias by lazy { MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) }

private fun createSharedPreferences(): SharedPreferences {
return EncryptedSharedPreferences.create(
FILE_NAME,
masterKeyAlias,
appContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal val sharedPrefs: SharedPreferences by lazy {
try {
createSharedPreferences()
} catch (e: Exception) {
val sharedPreferences = appContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
sharedPreferences.edit().clear().commit()
createSharedPreferences()
}
}

private val sharedPrefsEditor by lazy { sharedPrefs.edit() }

internal val deviceTokenUUID: String
get() {
return sharedPrefs.getString(PREFERENCE_KEY, null) ?: run {
val newDeviceToken = UUID.randomUUID().toString()
sharedPrefsEditor.putString(PREFERENCE_KEY, newDeviceToken)
sharedPrefsEditor.commit()
newDeviceToken
}
}

internal fun containsDeviceToken(): Boolean = sharedPrefs.contains(PREFERENCE_KEY)

internal val deviceToken: String
get() = deviceTokenUUID.filter { it.isLetterOrDigit() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,13 @@ internal class InteractContext private constructor(
): InteractContext? {
val codeChallenge = PkceGenerator.codeChallenge(codeVerifier)
val endpoints = client.endpointsOrNull() ?: return null
val urlBuilder = endpoints.issuer.newBuilder()
.addPathSegments("v1/interact")
val urlBuilder = endpoints.issuer.newBuilder().apply {
if (endpoints.issuer.pathSegments.contains("oauth2")) {
addPathSegments("v1/interact")
} else {
addPathSegments("oauth2/v1/interact")
}
}

val formBody = FormBody.Builder()
.add("client_id", client.configuration.clientId)
Expand Down
Loading

0 comments on commit 94a9e23

Please sign in to comment.