Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DT cookie and fix IDX for org auth servers #202

Merged
merged 3 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
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
14 changes: 14 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 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(private val client: OAuth2Client) {

Choose a reason for hiding this comment

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

I'm curious, is there a reason why the OAuth2Client is private? My Kotlin may be a bit rusty, but this will make it inaccessible to see by the developer, correct?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's correct. It's more of a legacy than an intentional decision to keep this private. I didn't think much about making this public because the developer can provide their own client to the constructor and have it available to them anyways. And it's also accessible to the developer through OAuth2Client.default if they construct the flow using the empty constructor. I can make this public

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