|
| 1 | +package com.example.identity.credentialmanager |
| 2 | + |
| 3 | +import android.app.Activity |
| 4 | +import android.content.Context |
| 5 | +import android.util.JsonWriter |
| 6 | +import android.util.Log |
| 7 | +import android.widget.Toast |
| 8 | +import androidx.credentials.CreateCredentialRequest |
| 9 | +import androidx.credentials.CreatePublicKeyCredentialRequest |
| 10 | +import androidx.credentials.CreatePublicKeyCredentialResponse |
| 11 | +import androidx.credentials.CredentialManager |
| 12 | +import androidx.credentials.GetCredentialRequest |
| 13 | +import androidx.credentials.GetCredentialResponse |
| 14 | +import androidx.credentials.GetPasswordOption |
| 15 | +import androidx.credentials.GetPublicKeyCredentialOption |
| 16 | +import androidx.credentials.PublicKeyCredential |
| 17 | +import androidx.credentials.exceptions.CreateCredentialException |
| 18 | +import com.example.identity.credentialmanager.ApiResult.Success |
| 19 | +import okhttp3.MediaType.Companion.toMediaTypeOrNull |
| 20 | +import okhttp3.OkHttpClient |
| 21 | +import okhttp3.Request.Builder |
| 22 | +import okhttp3.RequestBody |
| 23 | +import okhttp3.RequestBody.Companion.toRequestBody |
| 24 | +import okhttp3.Response |
| 25 | +import okhttp3.ResponseBody |
| 26 | +import org.json.JSONObject |
| 27 | +import java.io.StringWriter |
| 28 | +import ru.gildor.coroutines.okhttp.await |
| 29 | + |
| 30 | +class Fido2ToCredmanMigration( |
| 31 | + private val context: Context, |
| 32 | + private val client: OkHttpClient, |
| 33 | +) { |
| 34 | + private val BASE_URL = "" |
| 35 | + private val JSON = "".toMediaTypeOrNull() |
| 36 | + private val PUBLIC_KEY = "" |
| 37 | + |
| 38 | + // [START android_identity_fido2_credman_init] |
| 39 | + val credMan = CredentialManager.create(context) |
| 40 | + // [END android_identity_fido2_credman_init] |
| 41 | + |
| 42 | + // [START android_identity_fido2_migration_post_request_body] |
| 43 | + suspend fun registerRequest() { |
| 44 | + // ... |
| 45 | + Builder() |
| 46 | + .url("$BASE_URL/<your api url>") |
| 47 | + .method("POST", jsonRequestBody { |
| 48 | + name("attestation").value("none") |
| 49 | + name("authenticatorSelection").objectValue { |
| 50 | + name("residentKey").value("required") |
| 51 | + } |
| 52 | + }).build() |
| 53 | + // ... |
| 54 | + } |
| 55 | + // [END android_identity_fido2_migration_post_request_body] |
| 56 | + |
| 57 | + // [START android_identity_fido2_migration_register_request] |
| 58 | + suspend fun registerRequest(sessionId: String): ApiResult<JSONObject> { |
| 59 | + val call = client.newCall( |
| 60 | + Builder() |
| 61 | + .url("$BASE_URL/<your api url>") |
| 62 | + .addHeader("Cookie", formatCookie(sessionId)) |
| 63 | + .method("POST", jsonRequestBody { |
| 64 | + name("attestation").value("none") |
| 65 | + name("authenticatorSelection").objectValue { |
| 66 | + name("authenticatorAttachment").value("platform") |
| 67 | + name("userVerification").value("required") |
| 68 | + name("residentKey").value("required") |
| 69 | + } |
| 70 | + }).build() |
| 71 | + ) |
| 72 | + val response = call.await() |
| 73 | + return response.result("Error calling the api") { |
| 74 | + parsePublicKeyCredentialCreationOptions( |
| 75 | + body ?: throw ApiException("Empty response from the api call") |
| 76 | + ) |
| 77 | + } |
| 78 | + } |
| 79 | + // [END android_identity_fido2_migration_register_request] |
| 80 | + |
| 81 | + // [START android_identity_fido2_migration_create_passkey] |
| 82 | + suspend fun createPasskey( |
| 83 | + activity: Activity, |
| 84 | + requestResult: JSONObject |
| 85 | + ): CreatePublicKeyCredentialResponse? { |
| 86 | + val request = CreatePublicKeyCredentialRequest(requestResult.toString()) |
| 87 | + var response: CreatePublicKeyCredentialResponse? = null |
| 88 | + try { |
| 89 | + response = credMan.createCredential( |
| 90 | + request = request as CreateCredentialRequest, |
| 91 | + context = activity |
| 92 | + ) as CreatePublicKeyCredentialResponse |
| 93 | + } catch (e: CreateCredentialException) { |
| 94 | + |
| 95 | + showErrorAlert(activity, e) |
| 96 | + |
| 97 | + return null |
| 98 | + } |
| 99 | + return response |
| 100 | + } |
| 101 | + // [END android_identity_fido2_migration_create_passkey] |
| 102 | + |
| 103 | + // [START android_identity_fido2_migration_auth_with_passkeys] |
| 104 | + /** |
| 105 | + * @param sessionId The session ID to be used for the sign-in. |
| 106 | + * @param credentialId The credential ID of this device. |
| 107 | + * @return a JSON object. |
| 108 | + */ |
| 109 | + suspend fun signinRequest(): ApiResult<JSONObject> { |
| 110 | + val call = client.newCall(Builder().url(buildString { |
| 111 | + append("$BASE_URL/signinRequest") |
| 112 | + }).method("POST", jsonRequestBody {}) |
| 113 | + .build() |
| 114 | + ) |
| 115 | + val response = call.await() |
| 116 | + return response.result("Error calling /signinRequest") { |
| 117 | + parsePublicKeyCredentialRequestOptions( |
| 118 | + body ?: throw ApiException("Empty response from /signinRequest") |
| 119 | + ) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + /** |
| 124 | + * @param sessionId The session ID to be used for the sign-in. |
| 125 | + * @param response The JSONObject for signInResponse. |
| 126 | + * @param credentialId id/rawId. |
| 127 | + * @return A list of all the credentials registered on the server, |
| 128 | + * including the newly-registered one. |
| 129 | + */ |
| 130 | + suspend fun signinResponse( |
| 131 | + sessionId: String, response: JSONObject, credentialId: String |
| 132 | + ): ApiResult<Unit> { |
| 133 | + |
| 134 | + val call = client.newCall( |
| 135 | + Builder().url("$BASE_URL/signinResponse") |
| 136 | + .addHeader("Cookie",formatCookie(sessionId)) |
| 137 | + .method("POST", jsonRequestBody { |
| 138 | + name("id").value(credentialId) |
| 139 | + name("type").value(PUBLIC_KEY.toString()) |
| 140 | + name("rawId").value(credentialId) |
| 141 | + name("response").objectValue { |
| 142 | + name("clientDataJSON").value( |
| 143 | + response.getString("clientDataJSON") |
| 144 | + ) |
| 145 | + name("authenticatorData").value( |
| 146 | + response.getString("authenticatorData") |
| 147 | + ) |
| 148 | + name("signature").value( |
| 149 | + response.getString("signature") |
| 150 | + ) |
| 151 | + name("userHandle").value( |
| 152 | + response.getString("userHandle") |
| 153 | + ) |
| 154 | + } |
| 155 | + }).build() |
| 156 | + ) |
| 157 | + val apiResponse = call.await() |
| 158 | + return apiResponse.result("Error calling /signingResponse") { |
| 159 | + } |
| 160 | + } |
| 161 | + // [END android_identity_fido2_migration_auth_with_passkeys] |
| 162 | + |
| 163 | + // [START android_identity_fido2_migration_get_passkeys] |
| 164 | + suspend fun getPasskey( |
| 165 | + activity: Activity, |
| 166 | + creationResult: JSONObject |
| 167 | + ): GetCredentialResponse? { |
| 168 | + Toast.makeText( |
| 169 | + activity, |
| 170 | + "Fetching previously stored credentials", |
| 171 | + Toast.LENGTH_SHORT) |
| 172 | + .show() |
| 173 | + var result: GetCredentialResponse? = null |
| 174 | + try { |
| 175 | + val request= GetCredentialRequest( |
| 176 | + listOf( |
| 177 | + GetPublicKeyCredentialOption( |
| 178 | + creationResult.toString(), |
| 179 | + null |
| 180 | + ), |
| 181 | + GetPasswordOption() |
| 182 | + ) |
| 183 | + ) |
| 184 | + result = credMan.getCredential(activity, request) |
| 185 | + if (result.credential is PublicKeyCredential) { |
| 186 | + val publicKeycredential = result.credential as PublicKeyCredential |
| 187 | + Log.i("TAG", "Passkey ${publicKeycredential.authenticationResponseJson}") |
| 188 | + return result |
| 189 | + } |
| 190 | + } catch (e: Exception) { |
| 191 | + showErrorAlert(activity, e) |
| 192 | + } |
| 193 | + return result |
| 194 | + } |
| 195 | + // [END android_identity_fido2_migration_get_passkeys] |
| 196 | + |
| 197 | + private fun showErrorAlert( |
| 198 | + activity: Activity, |
| 199 | + e: Exception |
| 200 | + ) {} |
| 201 | + |
| 202 | + private fun jsonRequestBody(body: JsonWriter.() -> Unit): RequestBody { |
| 203 | + val output = StringWriter() |
| 204 | + JsonWriter(output).use { writer -> |
| 205 | + writer.beginObject() |
| 206 | + writer.body() |
| 207 | + writer.endObject() |
| 208 | + } |
| 209 | + return output.toString().toRequestBody(JSON) |
| 210 | + } |
| 211 | + |
| 212 | + private fun JsonWriter.objectValue(body: JsonWriter.() -> Unit) { |
| 213 | + beginObject() |
| 214 | + body() |
| 215 | + endObject() |
| 216 | + } |
| 217 | + |
| 218 | + private fun formatCookie(sessionId: String): String { |
| 219 | + return "" |
| 220 | + } |
| 221 | + |
| 222 | + private fun parsePublicKeyCredentialCreationOptions(body: ResponseBody): JSONObject { |
| 223 | + return JSONObject() |
| 224 | + } |
| 225 | + |
| 226 | + private fun parsePublicKeyCredentialRequestOptions(body: ResponseBody): JSONObject { |
| 227 | + return JSONObject() |
| 228 | + } |
| 229 | + |
| 230 | + private fun <T> Response.result(errorMessage: String, data: Response.() -> T): ApiResult<T> { |
| 231 | + return Success() |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +sealed class ApiResult<out R> { |
| 236 | + class Success<T>: ApiResult<T>() |
| 237 | +} |
| 238 | + |
| 239 | +class ApiException(message: String) : RuntimeException(message) |
0 commit comments