क्रेडेंशियल देने वाले अपने समाधान के साथ क्रेडेंशियल मैनेजर को इंटिग्रेट करें

Credential Manager, Android 14 में लॉन्च किए गए एपीआई का एक सेट है. यह उपयोगकर्ता नाम-पासवर्ड, पासकी, और फ़ेडरेटेड साइन-इन सलूशन (जैसे, 'Google से साइन इन करें') जैसे कई तरीकों से साइन इन करने की सुविधा देता है. Credential Manager API को कॉल करने पर, Android सिस्टम डिवाइस पर इंस्टॉल किए गए क्रेडेंशियल देने वाले सभी प्लैटफ़ॉर्म से क्रेडेंशियल इकट्ठा करता है. इस दस्तावेज़ में, एपीआई के उस सेट के बारे में बताया गया है जो क्रेडेंशियल देने वाले इन प्लैटफ़ॉर्म के लिए इंटिग्रेशन एंडपॉइंट उपलब्ध कराता है.

सेटअप

क्रेडेंशियल देने वाले प्लैटफ़ॉर्म में कोई सुविधा लागू करने से पहले, सेटअप के वे चरण पूरे करें जो अगले सेक्शन में दिखाए गए हैं.

डिपेंडेंसी की जानकारी देना

Credential Manager लाइब्रेरी का सबसे नया वर्शन इस्तेमाल करने के लिए, अपने ऐप्लिकेशन मॉड्यूल के बिल्ड स्क्रिप्ट में ये डिपेंडेंसी जोड़ें:

Kotlin

dependencies {
    implementation("androidx.credentials:credentials:1.7.0-alpha02")
}

Groovy

dependencies {
    implementation "androidx.credentials:credentials:1.7.0-alpha02"
}

मेनिफ़ेस्ट फ़ाइल में सेवा एलिमेंट की जानकारी देना

अपने ऐप्लिकेशन की मेनिफ़ेस्ट फ़ाइल AndroidManifest.xml में, androidx.credentials लाइब्रेरी से <service> CredentialProviderService क्लास को बढ़ाने वाली सेवा क्लास के लिए, declaration की जानकारी शामिल करें. जैसा कि यहां दिए गए उदाहरण में दिखाया गया है.

<service android:name=".MyCredentialProviderService"
    android:enabled="true"
    android:exported="true"
    android:label="My Credential Provider"
    android:icon="@mipmap/ic_launcher"
    android:permission="android.permission.BIND_CREDENTIAL_PROVIDER_SERVICE"
    tools:targetApi="upside_down_cake">
    <intent-filter>
        <action android:name="android.service.credentials.CredentialProviderService"/>
    </intent-filter>
    <meta-data
        android:name="android.credentials.provider"
        android:resource="@xml/provider"/>
</service>

पिछले उदाहरण में दिखाई गई अनुमति और इंटेंट फ़िल्टर, Credential Manager के फ़्लो के सही तरीके से काम करने के लिए ज़रूरी हैं. यह अनुमति इसलिए ज़रूरी है, ताकि सिर्फ़ Android सिस्टम इस सेवा से जुड़ सके. इंटेंट फ़िल्टर का इस्तेमाल, Credential Manager के लिए क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के तौर पर इस सेवा की खोज करने के लिए किया जाता है.

क्रेडेंशियल के उन टाइप की जानकारी देना जो इस्तेमाल किए जा सकते हैं

अपनी res/xml डायरेक्ट्री में, provider.xml नाम की नई फ़ाइल बनाएं. इस फ़ाइल में, क्रेडेंशियल के उन टाइप की जानकारी दें जिन्हें आपकी सेवा इस्तेमाल कर सकती है. इसके लिए, लाइब्रेरी में क्रेडेंशियल के हर टाइप के लिए तय किए गए कॉन्स्टैंट का इस्तेमाल करें. यहां दिए गए उदाहरण में, सेवा पारंपरिक पासवर्ड के साथ-साथ पासकी का भी इस्तेमाल कर सकती है. इनके लिए कॉन्स्टैंट, TYPE_PASSWORD_CREDENTIAL और TYPE_PUBLIC_KEY_CREDENTIAL के तौर पर तय किए गए हैं:

<credential-provider xmlns:android="http://schemas.android.com/apk/res/android">
    <capabilities>
        <capability name="android.credentials.TYPE_PASSWORD_CREDENTIAL" />
        <capability name="androidx.credentials.TYPE_PUBLIC_KEY_CREDENTIAL" />
    </capabilities>
</credential-provider>

एपीआई के पिछले लेवल पर, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म, पासवर्ड और अन्य डेटा के लिए अपने-आप जानकारी भरने की सुविधा जैसे एपीआई के साथ इंटिग्रेट होते हैं. ये प्लैटफ़ॉर्म, मौजूदा क्रेडेंशियल टाइप को सेव करने के लिए, उसी इंटरनल इन्फ़्रास्ट्रक्चर का इस्तेमाल कर सकते हैं. साथ ही, इसे पासकी सहित अन्य क्रेडेंशियल टाइप के लिए भी बढ़ाया जा सकता है.

प्लैटफ़ॉर्म के साथ इंटरैक्ट करने का दो चरणों वाला तरीका

Credential Manager, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के साथ दो चरणों में इंटरैक्ट करता है:

  1. पहला चरण, शुरू करने/क्वेरी करने का चरण है. इसमें सिस्टम, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म की सेवाओं से जुड़ता है और onBeginGetCredentialRequest(), onBeginCreateCredentialRequest(), या onClearCredentialStateRequest() तरीकों को Begin… अनुरोधों के साथ कॉल करता है. प्लैटफ़ॉर्म को इन अनुरोधों को प्रोसेस करना होगा और Begin… जवाब देने होंगे. साथ ही, इनमें वे एंट्री शामिल करनी होंगी जो खाता चुनने वाले टूल पर दिखाए जाने वाले विज़ुअल विकल्पों को दिखाती हैं. हर एंट्री के लिए, PendingIntent सेट करना होगा.
  2. जब उपयोगकर्ता कोई एंट्री चुनता है, तो चुनने का चरण शुरू होता है. साथ ही, एंट्री से जुड़ा PendingIntent ट्रिगर हो जाता है. इससे, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म की गतिविधि दिखती है. जब उपयोगकर्ता इस गतिविधि के साथ इंटरैक्ट कर लेता है, तो क्रेडेंशियल देने वाले प्लैटफ़ॉर्म को गतिविधि खत्म करने से पहले, जवाब को गतिविधि के नतीजे के तौर पर सेट करना होगा. इसके बाद, यह जवाब उस क्लाइंट ऐप्लिकेशन को भेजा जाता है जिसने Credential Manager को कॉल किया था.

पासकी बनाने की सुविधा को मैनेज करना

पासकी बनाने के अनुरोधों के लिए क्वेरी को मैनेज करना

जब कोई क्लाइंट ऐप्लिकेशन पासकी बनाना चाहता है और उसे क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के साथ सेव करना चाहता है, तो वह createCredential API को कॉल करता है. क्रेडेंशियल देने वाले प्लैटफ़ॉर्म की सेवा में इस अनुरोध को इस तरह से मैनेज करने के लिए कि पासकी आपके स्टोरेज में सेव हो जाए, अगले सेक्शन में दिखाए गए चरण पूरे करें.

  1. अपनी सेवा में, onBeginCreateCredentialRequest() तरीके को बदलें जो CredentialProviderService से बढ़ाई गई है.
  2. इससे जुड़ा corresponding BeginCreateCredentialResponse बनाकर और इसे कॉलबैक के ज़रिए पास करके, BeginCreateCredentialRequest को मैनेज करें.
  3. BeginCreateCredentialResponse बनाते समय, ज़रूरी CreateEntries जोड़ें. हर CreateEntry उस खाते से जुड़ी होनी चाहिए जिसमें क्रेडेंशियल सेव किया जा सकता है. साथ ही, इसमें अन्य ज़रूरी मेटाडेटा के साथ PendingIntent सेट होना चाहिए.

यहां दिए गए उदाहरण में, इन चरणों को लागू करने का तरीका बताया गया है.

override fun onBeginCreateCredentialRequest(
    request: BeginCreateCredentialRequest,
    cancellationSignal: CancellationSignal,
    callback: OutcomeReceiver<BeginCreateCredentialResponse, CreateCredentialException>,
) {
    val response: BeginCreateCredentialResponse? = processCreateCredentialRequest(request)
    if (response != null) {
        callback.onResult(response)
    } else {
        callback.onError(CreateCredentialUnknownException())
    }
}

fun processCreateCredentialRequest(request: BeginCreateCredentialRequest): BeginCreateCredentialResponse? {
    when (request) {
        is BeginCreatePublicKeyCredentialRequest -> {
            // Request is passkey type
            return handleCreatePasskeyQuery(request)
        }
    }
    // Request not supported
    return null
}

private fun handleCreatePasskeyQuery(
    request: BeginCreatePublicKeyCredentialRequest
): BeginCreateCredentialResponse {

    // Adding two create entries - one for storing credentials to the 'Personal'
    // account, and one for storing them to the 'Family' account. These
    // accounts are local to this sample app only.
    val createEntries: MutableList<CreateEntry> = mutableListOf()
    createEntries.add(
        CreateEntry(
            PERSONAL_ACCOUNT_ID,
            createNewPendingIntent(PERSONAL_ACCOUNT_ID, CREATE_PASSKEY_INTENT)
        )
    )

    createEntries.add(
        CreateEntry(
            FAMILY_ACCOUNT_ID,
            createNewPendingIntent(FAMILY_ACCOUNT_ID, CREATE_PASSKEY_INTENT)
        )
    )

    return BeginCreateCredentialResponse(createEntries)
}

private fun createNewPendingIntent(accountId: String, action: String): PendingIntent {
    val intent = Intent(action).setPackage(PACKAGE_NAME)

    // Add your local account ID as an extra to the intent, so that when
    // user selects this entry, the credential can be saved to this
    // account
    intent.putExtra(EXTRA_KEY_ACCOUNT_ID, accountId)

    return PendingIntent.getActivity(
        applicationContext, UNIQUE_REQ_CODE,
        intent,
        (
            PendingIntent.FLAG_MUTABLE
                or PendingIntent.FLAG_UPDATE_CURRENT
            )
    )
}

आपका PendingIntent निर्माण निम्नलिखित के अनुरूप होना चाहिए:

  • इससे जुड़ी ऐक्टिविटी को, ज़रूरी बायोमेट्रिक प्रॉम्प्ट, पुष्टि या चुने गए विकल्प दिखाने के लिए सेट अप किया जाना चाहिए.
  • जब इससे जुड़ी गतिविधि को कॉल किया जाता है, तब प्लैटफ़ॉर्म को जिस ज़रूरी डेटा की ज़रूरत होती है उसे उस इंटेंट पर एक्स्ट्रा के तौर पर सेट किया जाना चाहिए जिसका इस्तेमाल आपका PendingIntent बनाने के लिए किया जाता है. जैसे, बनाने के फ़्लो में accountId.
  • आपका PendingIntent PendingIntent.FLAG_MUTABLE फ़्लैग के साथ बनाया जाना चाहिए, ताकि सिस्टम इंटेंट एक्स्ट्रा में फ़ाइनल अनुरोध जोड़ सके.
  • आपका PendingIntent फ़्लैग PendingIntent.FLAG_ONE_SHOT के साथ नहीं बनाया जाना चाहिए, क्योंकि उपयोगकर्ता कोई एंट्री चुन सकता है, वापस जा सकता है, और उसे फिर से चुन सकता है. इससे PendingIntent दो बार ट्रिगर होगा.
  • आपका PendingIntent, यूनीक अनुरोध कोड के साथ बनाया जाना चाहिए, ताकि हर एंट्री का अपना PendingIntent हो सके.

पासकी बनाने के अनुरोधों के लिए एंट्री चुनने की सुविधा को मैनेज करना

  1. जब उपयोगकर्ता पहले से भरी गई CreateEntry चुनता है, तो इससे जुड़ा PendingIntent कॉल होता है और प्लैटफ़ॉर्म का Activity बनता है.
  2. अपनी ऐक्टिविटी का onCreate तरीका कॉल होने के बाद, इससे जुड़े इंटेंट को ऐक्सेस करें और ProviderCreateCredentialRequest पाने के लिए, इसे PendingIntentHander क्लास में पास करें.
  3. अनुरोध से requestJson, callingAppInfo, और clientDataHash निकालें.
  4. इंटेंट एक्स्ट्रा से, स्थानीय accountId निकालें. यह सैंपल ऐप्लिकेशन के लिए खास तौर पर लागू किया गया है और यह ज़रूरी नहीं है. इस खाता आईडी का इस्तेमाल, इस क्रेडेंशियल को इस खास खाता आईडी के लिए सेव करने के लिए किया जा सकता है.
  5. requestJson की पुष्टि करें. यहां दिए गए उदाहरण में, इनपुट JSON को WebAuthn की खास जानकारी के मुताबिक, स्ट्रक्चर्ड क्लास में बदलने के लिए, स्थानीय डेटा क्लास का इस्तेमाल किया गया है. जैसे, PublicKeyCredentialCreationOptions. क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के तौर पर, इसे अपने पार्सर से बदला जा सकता है.
  6. अगर कॉल, नेटिव Android ऐप्लिकेशन से किया गया है, तो कॉल करने वाले ऐप्लिकेशन के लिए एसेट-लिंक की जांच करें.
  7. पुष्टि करने का प्रॉम्प्ट दिखाएं. यहां दिए गए उदाहरण में, Android Biometric API का इस्तेमाल किया गया है.
  8. पुष्टि होने के बाद, credentialId और कुंजी का जोड़ा जनरेट करें.
  9. अपने स्थानीय डेटाबेस में callingAppInfo.packageName के लिए, निजी कुंजी को सेव करें.
  10. एक Web Authentication API JSON जवाब बनाएं. इसमें सार्वजनिक कुंजी और credentialId शामिल हो. यहां दिए गए उदाहरण में, स्थानीय यूटिलिटी क्लास का इस्तेमाल किया गया है. जैसे, AuthenticatorAttestationResponse और FidoPublicKeyCredential. इनकी मदद से, पहले बताई गई खास जानकारी के आधार पर JSON बनाया जा सकता है.क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के तौर पर, इन क्लास को अपने बिल्डर से बदला जा सकता है.
  11. ऊपर जनरेट किए गए JSON की मदद से, CreatePublicKeyCredentialResponse बनाएं.
  12. CreatePublicKeyCredentialResponse को Intent पर एक्स्ट्रा के तौर पर सेट करें PendingIntentHander.setCreateCredentialResponse(). साथ ही, उस इंटेंट को ऐक्टिविटी के नतीजे के तौर पर सेट करें.
  13. गतिविधि खत्म करें.

यहां दिए गए कोड के उदाहरण में, इन चरणों को दिखाया गया है. onCreate() को कॉल करने के बाद, इस कोड को अपनी गतिविधि क्लास में मैनेज करना होगा.

override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
    super.onCreate(savedInstanceState, persistentState)
    // ...

    val request =
        PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent)

    val accountId = intent.getStringExtra(CredentialsRepo.EXTRA_KEY_ACCOUNT_ID)
    if (request != null && request.callingRequest is CreatePublicKeyCredentialRequest) {
        val publicKeyRequest: CreatePublicKeyCredentialRequest =
            request.callingRequest as CreatePublicKeyCredentialRequest
        createPasskey(
            publicKeyRequest.requestJson,
            request.callingAppInfo,
            publicKeyRequest.clientDataHash,
            accountId
        )
    }
}

@SuppressLint("RestrictedApi")
fun createPasskey(
    requestJson: String,
    callingAppInfo: CallingAppInfo?,
    clientDataHash: ByteArray?,
    accountId: String?
) {
    val request = PublicKeyCredentialCreationOptions(requestJson)

    val biometricPrompt = BiometricPrompt(
        this,
        { }, // Pass in your own executor
        object : AuthenticationCallback() {
            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                super.onAuthenticationError(errorCode, errString)
                finish()
            }

            override fun onAuthenticationFailed() {
                super.onAuthenticationFailed()
                finish()
            }

            @RequiresApi(VERSION_CODES.P)
            override fun onAuthenticationSucceeded(
                result: AuthenticationResult
            ) {
                super.onAuthenticationSucceeded(result)

                // Generate a credentialId
                val credentialId = ByteArray(32)
                SecureRandom().nextBytes(credentialId)

                // Generate a credential key pair
                val spec = ECGenParameterSpec("secp256r1")
                val keyPairGen = KeyPairGenerator.getInstance("EC")
                keyPairGen.initialize(spec)
                val keyPair = keyPairGen.genKeyPair()

                // Save passkey in your database as per your own implementation

                // Create AuthenticatorAttestationResponse object to pass to
                // FidoPublicKeyCredential

                val response = AuthenticatorAttestationResponse(
                    requestOptions = request,
                    credentialId = credentialId,
                    credentialPublicKey = getPublicKeyFromKeyPair(keyPair),
                    origin = appInfoToOrigin(callingAppInfo!!),
                    up = true,
                    uv = true,
                    be = true,
                    bs = true,
                    packageName = callingAppInfo.packageName
                )

                val credential = FidoPublicKeyCredential(
                    rawId = credentialId,
                    response = response,
                    authenticatorAttachment = "", // Add your authenticator attachment
                )
                val result = Intent()

                val createPublicKeyCredResponse =
                    CreatePublicKeyCredentialResponse(credential.json())

                // Set the CreateCredentialResponse as the result of the Activity
                PendingIntentHandler.setCreateCredentialResponse(
                    result,
                    createPublicKeyCredResponse
                )
                setResult(RESULT_OK, result)
                finish()
            }
        }
    )

    val promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("Use your screen lock")
        .setSubtitle("Create passkey for ${request.rp.name}")
        .setAllowedAuthenticators(
            BiometricManager.Authenticators.BIOMETRIC_STRONG
            /* or BiometricManager.Authenticators.DEVICE_CREDENTIAL */
        )
        .build()
    biometricPrompt.authenticate(promptInfo)
}

@RequiresApi(VERSION_CODES.P)
fun appInfoToOrigin(info: CallingAppInfo): String {
    val cert = info.signingInfo.apkContentsSigners[0].toByteArray()
    val md = MessageDigest.getInstance("SHA-256")
    val certHash = md.digest(cert)
    // This is the format for origin
    return "android:apk-key-hash:${b64Encode(certHash)}"
}

पासवर्ड बनाने के अनुरोधों के लिए क्वेरी को मैनेज करना

पासवर्ड बनाने के अनुरोधों के लिए क्वेरी को मैनेज करने के लिए, यह तरीका अपनाएं:

  • पिछले सेक्शन में बताए गए processCreateCredentialRequest() तरीके में, पासवर्ड के अनुरोधों को मैनेज करने के लिए, स्विच ब्लॉक में एक और केस जोड़ें.
  • BeginCreateCredentialResponse बनाते समय, ज़रूरी CreateEntries जोड़ें.
  • हर CreateEntry उस खाते से जुड़ी होनी चाहिए जिसमें क्रेडेंशियल सेव किया जा सकता है. साथ ही, इसमें अन्य मेटाडेटा के साथ PendingIntent सेट होना चाहिए.

यहां दिए गए उदाहरण में, इन चरणों को लागू करने का तरीका बताया गया है:

fun processCreateCredentialRequest(
    request: BeginCreateCredentialRequest
): BeginCreateCredentialResponse? {
    when (request) {
        is BeginCreatePublicKeyCredentialRequest -> {
            // Request is passkey type
            return handleCreatePasskeyQuery(request)
        }

        is BeginCreatePasswordCredentialRequest -> {
            // Request is password type
            return handleCreatePasswordQuery(request)
        }
    }
    return null
}

@RequiresApi(VERSION_CODES.M)
private fun handleCreatePasswordQuery(
    request: BeginCreatePasswordCredentialRequest
): BeginCreateCredentialResponse {
    val createEntries: MutableList<CreateEntry> = mutableListOf()

    // Adding two create entries - one for storing credentials to the 'Personal'
    // account, and one for storing them to the 'Family' account. These
    // accounts are local to this sample app only.
    createEntries.add(
        CreateEntry(
            PERSONAL_ACCOUNT_ID,
            createNewPendingIntent(PERSONAL_ACCOUNT_ID, CREATE_PASSWORD_INTENT)
        )
    )
    createEntries.add(
        CreateEntry(
            FAMILY_ACCOUNT_ID,
            createNewPendingIntent(FAMILY_ACCOUNT_ID, CREATE_PASSWORD_INTENT)
        )
    )

    return BeginCreateCredentialResponse(createEntries)
}

पासवर्ड बनाने के अनुरोधों के लिए एंट्री चुनने की सुविधा को मैनेज करना

जब उपयोगकर्ता भरी गई CreateEntry चुनता है, तो इससे जुड़ा PendingIntent काम करता है और इससे जुड़ी ऐक्टिविटी दिखती है. onCreate में पास किए गए, इससे जुड़े इंटेंट को ऐक्सेस करें और ProviderCreateCredentialRequest तरीका पाने के लिए, इसे PendingIntentHander क्लास में पास करें.

यहां दिए गए उदाहरण में, इस प्रोसेस को लागू करने का तरीका बताया गया है. इस कोड को अपनी गतिविधि के onCreate() तरीके में मैनेज करना होगा.

val createRequest = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent)
val accountId = intent.getStringExtra(CredentialsRepo.EXTRA_KEY_ACCOUNT_ID)

if (createRequest == null) {
    return
}

val request: CreatePasswordRequest = createRequest.callingRequest as CreatePasswordRequest

// Fetch the ID and password from the request and save it in your database
mDatabase.addNewPassword(
    PasswordInfo(
        request.id,
        request.password,
        createRequest.callingAppInfo.packageName
    )
)

// Set the final response back
val result = Intent()
val response = CreatePasswordResponse()
PendingIntentHandler.setCreateCredentialResponse(result, response)
setResult(Activity.RESULT_OK, result)
finish()

उपयोगकर्ता के साइन-इन को मैनेज करना

उपयोगकर्ता के साइन-इन को इन चरणों में मैनेज किया जाता है:

  • जब कोई क्लाइंट ऐप्लिकेशन किसी उपयोगकर्ता को साइन इन कराने की कोशिश करता है, तो वह GetCredentialRequest इंस्टेंस तैयार करता है.
  • Android फ़्रेमवर्क, इन सेवाओं से जुड़कर, इस अनुरोध को क्रेडेंशियल देने वाले सभी प्लैटफ़ॉर्म तक पहुंचाता है.
  • इसके बाद, प्लैटफ़ॉर्म की सेवा को BeginGetCredentialRequest मिलता है. इसमें BeginGetCredentialOption की सूची होती है. इनमें से हर एक में ऐसे पैरामीटर होते हैं जिनका इस्तेमाल, मिलते-जुलते क्रेडेंशियल पाने के लिए किया जा सकता है.

क्रेडेंशियल देने वाले प्लैटफ़ॉर्म की सेवा में इस अनुरोध को मैनेज करने के लिए, यह तरीका अपनाएं:

  1. अनुरोध को मैनेज करने के लिए, onBeginGetCredentialRequest() तरीके को बदलें. ध्यान दें कि अगर आपके क्रेडेंशियल लॉक हैं, तो जवाब में तुरंत AuthenticationAction सेट किया जा सकता है और कॉलबैक को कॉल किया जा सकता है.

    private val unlockEntryTitle = "Authenticate to continue"
    
    override fun onBeginGetCredentialRequest(
        request: BeginGetCredentialRequest,
        cancellationSignal: CancellationSignal,
        callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,
    ) {
        if (isAppLocked()) {
            callback.onResult(
                BeginGetCredentialResponse(
                    authenticationActions = mutableListOf(
                        AuthenticationAction(
                            unlockEntryTitle, createUnlockPendingIntent()
                        )
                    )
                )
            )
            return
        }
        try {
            response = processGetCredentialRequest(request)
            callback.onResult(response)
        } catch (e: GetCredentialException) {
            callback.onError(GetCredentialUnknownException())
        }
    }
    

    जिन प्लैटफ़ॉर्म को credentialEntries दिखाने से पहले क्रेडेंशियल अनलॉक करने की ज़रूरत होती है उन्हें एक पेंडिंग इंटेंट सेट अप करना होगा. इससे उपयोगकर्ता को ऐप्लिकेशन के अनलॉक फ़्लो पर ले जाया जाता है:

    private fun createUnlockPendingIntent(): PendingIntent {
        val intent = Intent(UNLOCK_INTENT).setPackage(PACKAGE_NAME)
        return PendingIntent.getActivity(
            applicationContext, UNIQUE_REQUEST_CODE, intent,
            (
                PendingIntent.FLAG_MUTABLE
                    or PendingIntent.FLAG_UPDATE_CURRENT
                )
        )
    }
    
  2. अपने स्थानीय डेटाबेस से क्रेडेंशियल वापस पाएं और उन्हें चुनने वाले टूल पर दिखाने के लिए, CredentialEntries का इस्तेमाल करके सेट अप करें. पासकी के लिए, इंटेंट पर credentialId को एक्स्ट्रा के तौर पर सेट किया जा सकता है, ताकि यह पता चल सके कि जब उपयोगकर्ता इस एंट्री को चुनता है, तो यह किस क्रेडेंशियल से मैप होती है.

    companion object {
        // These intent actions are specified for corresponding activities
        // that are to be invoked through the PendingIntent(s)
        private const val GET_PASSKEY_INTENT_ACTION = "PACKAGE_NAME.GET_PASSKEY"
        private const val GET_PASSWORD_INTENT_ACTION = "PACKAGE_NAME.GET_PASSWORD"
    }
    
    fun processGetCredentialRequest(
        request: BeginGetCredentialRequest
    ): BeginGetCredentialResponse {
        val callingPackageInfo = request.callingAppInfo
        val callingPackageName = callingPackageInfo?.packageName.orEmpty()
        val credentialEntries: MutableList<CredentialEntry> = mutableListOf()
    
        for (option in request.beginGetCredentialOptions) {
            when (option) {
                is BeginGetPasswordOption -> {
                    credentialEntries.addAll(
                        populatePasswordData(
                            callingPackageName,
                            option
                        )
                    )
                }
                is BeginGetPublicKeyCredentialOption -> {
                    credentialEntries.addAll(
                        populatePasskeyData(
                            callingPackageInfo,
                            option
                        )
                    )
                } else -> {
                    Log.i(TAG, "Request not supported")
                }
            }
        }
        return BeginGetCredentialResponse(credentialEntries)
    }
    
  3. अपने डेटाबेस से क्रेडेंशियल की क्वेरी करें. साथ ही, पासकी और पासवर्ड की एंट्री बनाएं, ताकि उन्हें भरा जा सके.

    private fun populatePasskeyData(
        callingAppInfo: CallingAppInfo?,
        option: BeginGetPublicKeyCredentialOption
    ): List<CredentialEntry> {
        val passkeyEntries: MutableList<CredentialEntry> = mutableListOf()
        val request = PublicKeyCredentialRequestOptions(option.requestJson)
        // Get your credentials from database where you saved during creation flow
        val creds = getCredentialsFromInternalDb(request.rpId)
        val passkeys = creds.passkeys
        for (passkey in passkeys) {
            val data = Bundle()
            data.putString("credId", passkey.credId)
            passkeyEntries.add(
                PublicKeyCredentialEntry(
                    context = applicationContext,
                    username = passkey.username,
                    pendingIntent = createNewPendingIntent(
                        GET_PASSKEY_INTENT_ACTION,
                        data
                    ),
                    beginGetPublicKeyCredentialOption = option,
                    displayName = passkey.displayName,
                    icon = passkey.icon
                )
            )
        }
        return passkeyEntries
    }
    
    // Fetch password credentials and create password entries to populate to the user
    private fun populatePasswordData(
        callingPackage: String,
        option: BeginGetPasswordOption
    ): List<CredentialEntry> {
        val passwordEntries: MutableList<CredentialEntry> = mutableListOf()
    
        // Get your password credentials from database where you saved during
        // creation flow
        val creds = getCredentialsFromInternalDb(callingPackage)
        val passwords = creds.passwords
        for (password in passwords) {
            passwordEntries.add(
                PasswordCredentialEntry(
                    context = applicationContext,
                    username = password.username,
                    pendingIntent = createNewPendingIntent(
                        GET_PASSWORD_INTENT
                    ),
                    beginGetPasswordOption = option,
                    displayName = password.username,
                    icon = password.icon
                )
            )
        }
        return passwordEntries
    }
    
    private fun createNewPendingIntent(
        action: String,
        extra: Bundle? = null
    ): PendingIntent {
        val intent = Intent(action).setPackage(PACKAGE_NAME)
        if (extra != null) {
            intent.putExtra("CREDENTIAL_DATA", extra)
        }
    
        return PendingIntent.getActivity(
            applicationContext, UNIQUE_REQUEST_CODE, intent,
            (PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
        )
    }
    
  4. क्रेडेंशियल की क्वेरी करने और उन्हें भरने के बाद, अब आपको उपयोगकर्ता के चुने गए क्रेडेंशियल के लिए, चुनने के चरण को मैनेज करना होगा. भले ही, वह पासकी हो या पासवर्ड.

पासकी के लिए उपयोगकर्ता के चुने गए विकल्प को मैनेज करना

  1. इससे जुड़ी ऐक्टिविटी के onCreate तरीके में, इससे जुड़े इंटेंट को वापस पाएं और PendingIntentHandler.retrieveProviderGetCredentialRequest() को पास करें.
  2. ऊपर वापस पाए गए अनुरोध से, GetPublicKeyCredentialOption निकालें. इसके बाद, इस विकल्प से requestJson और clientDataHash निकालें.
  3. इंटेंट एक्स्ट्रा से credentialId निकालें. इसे क्रेडेंशियल देने वाले प्लैटफ़ॉर्म ने तब भरा था, जब इससे जुड़ा PendingIntent सेट अप किया गया था.
  4. ऊपर ऐक्सेस किए गए अनुरोध के पैरामीटर का इस्तेमाल करके, अपने स्थानीय डेटाबेस से पासकी निकालें.
  5. पुष्टि करें कि पासकी, निकाले गए मेटाडेटा और उपयोगकर्ता की पुष्टि के साथ मान्य है.

    val getRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent)
    val publicKeyRequest = getRequest?.credentialOptions?.first() as GetPublicKeyCredentialOption
    
    val requestInfo = intent.getBundleExtra("CREDENTIAL_DATA")
    val credIdEnc = requestInfo?.getString("credId").orEmpty()
    
    // Get the saved passkey from your database based on the credential ID from the PublicKeyRequest
    val passkey = mDatabase.getPasskey(credIdEnc)
    
    // Decode the credential ID, private key and user ID
    val credId = b64Decode(credIdEnc)
    val privateKey = b64Decode(passkey.credPrivateKey)
    val uid = b64Decode(passkey.uid)
    
    val origin = appInfoToOrigin(getRequest.callingAppInfo)
    val packageName = getRequest.callingAppInfo.packageName
    
    validatePasskey(
        publicKeyRequest.requestJson,
        origin,
        packageName,
        uid,
        passkey.username,
        credId,
        privateKey
    )
    
  6. उपयोगकर्ता की पुष्टि करने के लिए, बायोमेट्रिक प्रॉम्प्ट (या पुष्टि करने का कोई अन्य तरीका) दिखाएं. यहां दिए गए कोड स्निपेट में, Android Biometric API का इस्तेमाल किया गया है.

  7. पुष्टि होने के बाद, W3 Web Authentication Assertion की खास जानकारी के आधार पर, JSON जवाब बनाएं. यहां दिए गए कोड स्निपेट में, स्ट्रक्चर्ड पैरामीटर लेने और उन्हें ज़रूरी JSON फ़ॉर्मैट में बदलने के लिए, हेल्पर डेटा क्लास का इस्तेमाल किया गया है. जैसे, AuthenticatorAssertionResponse. जवाब में, WebAuthn क्रेडेंशियल की निजी कुंजी से डिजिटल सिग्नेचर शामिल होता है. Relying Party का सर्वर, साइन इन करने से पहले उपयोगकर्ता की पुष्टि करने के लिए, इस सिग्नेचर की पुष्टि कर सकता है.

  8. ऊपर जनरेट किए गए JSON का इस्तेमाल करके, PublicKeyCredential बनाएं और इसे फ़ाइनल GetCredentialResponse पर सेट करें. इस फ़ाइनल जवाब को इस गतिविधि के नतीजे के तौर पर सेट करें.

यहां दिए गए उदाहरण में, इन चरणों को लागू करने का तरीका बताया गया है:

val request = PublicKeyCredentialRequestOptions(requestJson)
val privateKey: ECPrivateKey = convertPrivateKey(privateKeyBytes)

val biometricPrompt = BiometricPrompt(
    this,
    { }, // Pass in your own executor
    object : BiometricPrompt.AuthenticationCallback() {
        override fun onAuthenticationError(
            errorCode: Int,
            errString: CharSequence
        ) {
            super.onAuthenticationError(errorCode, errString)
            finish()
        }

        override fun onAuthenticationFailed() {
            super.onAuthenticationFailed()
            finish()
        }

        override fun onAuthenticationSucceeded(
            result: BiometricPrompt.AuthenticationResult
        ) {
            super.onAuthenticationSucceeded(result)
            val response = AuthenticatorAssertionResponse(
                requestOptions = request,
                credentialId = credId,
                origin = origin,
                up = true,
                uv = true,
                be = true,
                bs = true,
                userHandle = uid,
                packageName = packageName
            )

            val sig = Signature.getInstance("SHA256withECDSA")
            sig.initSign(privateKey)
            sig.update(response.dataToSign())
            response.signature = sig.sign()

            val credential = FidoPublicKeyCredential(
                rawId = credId,
                response = response,
                authenticatorAttachment = "", // Add your authenticator attachment
            )
            val result = Intent()
            val passkeyCredential = PublicKeyCredential(credential.json())
            PendingIntentHandler.setGetCredentialResponse(
                result, GetCredentialResponse(passkeyCredential)
            )
            setResult(RESULT_OK, result)
            finish()
        }
    }
)

val promptInfo = BiometricPrompt.PromptInfo.Builder()
    .setTitle("Use your screen lock")
    .setSubtitle("Use passkey for ${request.rpId}")
    .setAllowedAuthenticators(
        BiometricManager.Authenticators.BIOMETRIC_STRONG
        /* or BiometricManager.Authenticators.DEVICE_CREDENTIAL */
    )
    .build()
biometricPrompt.authenticate(promptInfo)

पासवर्ड से पुष्टि के लिए उपयोगकर्ता के चुने गए विकल्प को मैनेज करना

  1. इससे जुड़ी गतिविधि में, onCreate में पास किए गए इंटेंट को ऐक्सेस करें और ProviderGetCredentialRequest का इस्तेमाल करके PendingIntentHandler निकालें.
  2. आने वाले पैकेज के नाम के लिए पासवर्ड क्रेडेंशियल वापस पाने के लिए, अनुरोध में GetPasswordOption का इस्तेमाल करें.

    val getRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent)
    
    val passwordOption = getRequest?.credentialOptions?.first() as GetPasswordOption
    
    val username = passwordOption.allowedUserIds.first()
    // Fetch the credentials for the calling app package name
    val creds = mDatabase.getCredentials(callingAppInfo.packageName)
    val passwords = creds.passwords
    val it = passwords.iterator()
    var password = ""
    while (it.hasNext()) {
        val passwordItemCurrent = it.next()
        if (passwordItemCurrent.username == username) {
            password = passwordItemCurrent.password
            break
        }
    }
    
  3. वापस पाने के बाद, चुने गए पासवर्ड क्रेडेंशियल के लिए जवाब सेट करें.

    // Set the response back
    val result = Intent()
    val passwordCredential = PasswordCredential(username, password)
    PendingIntentHandler.setGetCredentialResponse(
        result, GetCredentialResponse(passwordCredential)
    )
    setResult(Activity.RESULT_OK, result)
    finish()
    

पुष्टि करने की कार्रवाई की एंट्री चुनने की सुविधा को मैनेज करना

जैसा कि पहले बताया गया है, अगर क्रेडेंशियल लॉक हैं, तो क्रेडेंशियल देने वाला प्लैटफ़ॉर्म AuthenticationAction सेट कर सकता है. अगर उपयोगकर्ता इस एंट्री को चुनता है, तो PendingIntent में सेट किए गए इंटेंट ऐक्शन से जुड़ी गतिविधि कॉल होती है. इसके बाद, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म, क्रेडेंशियल अनलॉक करने के लिए, बायोमेट्रिक पुष्टि का फ़्लो या इसी तरह का कोई तरीका दिखा सकते हैं. सफलता मिलने पर, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म को BeginGetCredentialResponse बनाना होगा. यह ठीक उसी तरह से बनाया जाता है जैसे उपयोगकर्ता के साइन-इन को मैनेज करने के बारे में ऊपर बताया गया है, क्योंकि अब क्रेडेंशियल अनलॉक हो गए हैं. इसके बाद, तैयार किए गए इंटेंट को नतीजे के तौर पर सेट करने और गतिविधि खत्म करने से पहले, इस जवाब को PendingIntentHandler.setBeginGetCredentialResponse() तरीके से सेट करना होगा.

क्रेडेंशियल के अनुरोध मिटाना

कोई क्लाइंट ऐप्लिकेशन, क्रेडेंशियल चुनने के लिए सेव किए गए किसी भी स्टेट को मिटाने का अनुरोध कर सकता है. जैसे, हो सकता है कि क्रेडेंशियल देने वाला प्लैटफ़ॉर्म, पहले चुने गए क्रेडेंशियल को याद रखे और अगली बार सिर्फ़ वही क्रेडेंशियल दिखाए. कोई क्लाइंट ऐप्लिकेशन इस एपीआई को कॉल करता है और उम्मीद करता है कि चिपके हुए चुने गए विकल्प को मिटा दिया जाएगा. क्रेडेंशियल देने वाले प्लैटफ़ॉर्म की सेवा इस अनुरोध को मैनेज करने के लिए onClearCredentialStateRequest() तरीके को बदल सकती है:

override fun onClearCredentialStateRequest(
    request: ProviderClearCredentialStateRequest,
    cancellationSignal: CancellationSignal,
    callback: OutcomeReceiver<Void?, ClearCredentialException>
) {
    // Delete any maintained state as appropriate.
}

अपने उपयोगकर्ताओं को पासवर्ड, पासकी, और अपने-आप जानकारी भरने की सुविधा वाली स्क्रीन से, अपने प्लैटफ़ॉर्म की सेटिंग खोलने की अनुमति देने के लिए, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के ऐप्लिकेशन को res/xml/provider.xml में, credential-provider settingsActivity मेनिफ़ेस्ट एट्रिब्यूट को लागू करना चाहिए. इस एट्रिब्यूट की मदद से, इंटेंट का इस्तेमाल करके अपने ऐप्लिकेशन की सेटिंग वाली स्क्रीन खोली जा सकती है. ऐसा तब होता है, जब कोई उपयोगकर्ता पासवर्ड, पासकी, और अपने-आप जानकारी भरने की सुविधा वाली सेवाओं की सूची में, किसी प्लैटफ़ॉर्म के नाम पर क्लिक करता है. इस एट्रिब्यूट की वैल्यू को, सेटिंग स्क्रीन से लॉन्च की जाने वाली गतिविधि के नाम पर सेट करें.

<credential-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:settingsSubtitle="Example settings provider name"
    android:settingsActivity="com.example.SettingsActivity">
    <capabilities>
        <capability name="android.credentials.TYPE_PUBLIC_KEY_CREDENTIAL" />
    </capabilities>
</credential-provider>
बदलाव और खोलने के बटन के फ़ंक्शन दिखाने वाला डायग्राम
पहली इमेज: **बदलें** बटन, मौजूदा चुनने का डायलॉग खोलता है. इससे उपयोगकर्ता, क्रेडेंशियल देने वाले अपने पसंदीदा प्लैटफ़ॉर्म को चुन सकता है. खोलें बटन, मेनिफ़ेस्ट में तय की गई सेटिंग वाली गतिविधि लॉन्च करता है. साथ ही, उस प्लैटफ़ॉर्म के लिए खास तौर पर सेटिंग पेज खोलता है.

सेटिंग के इंटेंट

सेटिंग खोलें: android.settings.CREDENTIAL_PROVIDER इंटेंट सेटिंग वाली स्क्रीन खोलता है. यहां उपयोगकर्ता, क्रेडेंशियल देने वाले अपने पसंदीदा और अन्य प्लैटफ़ॉर्म चुन सकता है.

पासवर्ड, पासकी, और ऑटोमैटिक भरने की सेटिंग वाली स्क्रीन
दूसरी इमेज: पासवर्ड, पासकी, और अपने-आप जानकारी भरने की सुविधा वाली सेटिंग स्क्रीन.

क्रेडेंशियल देने वाली पसंदीदा सेवा: ACTION_REQUEST_SET_AUTOFILL_SERVICE इंटेंट, आपके उपयोगकर्ता को क्रेडेंशियल देने वाले पसंदीदा प्लैटफ़ॉर्म को चुनने वाली स्क्रीन पर रीडायरेक्ट करता है. इस स्क्रीन पर चुना गया प्लैटफ़ॉर्म, क्रेडेंशियल देने वाला पसंदीदा प्लैटफ़ॉर्म और अपने-आप जानकारी भरने की सुविधा देने वाला प्लैटफ़ॉर्म बन जाता है.

बदलाव और खोलने के बटन के फ़ंक्शन दिखाने वाला डायग्राम
तीसरी इमेज: पासवर्ड, पासकी, और अपने-आप जानकारी भरने की सुविधा के लिए, पसंदीदा सेवा की सेटिंग स्क्रीन.

अनुमति वाली सूची पाना, जिसमें खास अधिकारों वाले ऐप्लिकेशन शामिल हों

वेब ब्राउज़र जैसे खास अधिकारों वाले ऐप्लिकेशन, Credential Manager के GetCredentialRequest() और CreatePublicKeyCredentialRequest() तरीकों में origin पैरामीटर सेट करके, अन्य Relying Party की ओर से Credential Manager को कॉल करते हैं. इन अनुरोधों को प्रोसेस करने के लिए, क्रेडेंशियल देने वाला प्लैटफ़ॉर्म, getOrigin()API का इस्तेमाल करके origin वापस पाता है.

origin वापस पाने के लिए, क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के ऐप्लिकेशन को, खास अधिकारों वाले और भरोसेमंद कॉल करने वालों की सूची, androidx.credentials.provider.CallingAppInfo's getOrigin() API में पास करनी होगी. यह अनुमति वाली सूची, मान्य JSON ऑब्जेक्ट होनी चाहिए. origin तब वापस मिलता है, जब packageName और signingInfo से मिले सर्टिफ़िकेट फ़िंगरप्रिंट, getOrigin() API में पास किए गए privilegedAllowlist में मौजूद किसी ऐप्लिकेशन के फ़िंगरप्रिंट से मेल खाते हैं. origin की वैल्यू मिलने के बाद, प्लैटफ़ॉर्म के ऐप्लिकेशन को इसे खास अधिकारों वाला कॉल मानना चाहिए. साथ ही, कॉल करने वाले ऐप्लिकेशन के सिग्नेचर का इस्तेमाल करके origin की गिनती करने के बजाय, इसे origin क्लाइंट डेटा में AuthenticatorResponse पर सेट करना चाहिए.

अगर आपको origin वापस मिलता है, तो सिग्नेचर के अनुरोध के दौरान clientDataJSON को इकट्ठा और हैश करने के बजाय, CreatePublicKeyCredentialRequest() या GetPublicKeyCredentialOption() में सीधे तौर पर दिए गए clientDataHash का इस्तेमाल करें. JSON पार्स करने से जुड़ी समस्याओं से बचने के लिए, अटेस्टेशन और असर्शन के जवाब में clientDataJSON के लिए प्लेसहोल्डर वैल्यू सेट करें. Google Password Manager, getOrigin() को कॉल करने के लिए, खुले तौर पर उपलब्ध अनुमति वाली सूची का इस्तेमाल करता है. क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के तौर पर, इस सूची का इस्तेमाल किया जा सकता है या एपीआई में बताए गए JSON फ़ॉर्मैट में अपनी सूची दी जा सकती है. यह प्लैटफ़ॉर्म पर निर्भर करता है कि वह किस सूची का इस्तेमाल करता है. तीसरे पक्ष के क्रेडेंशियल देने वाले प्लैटफ़ॉर्म के साथ खास अधिकारों वाला ऐक्सेस पाने के लिए, तीसरे पक्ष की ओर से उपलब्ध कराए गए दस्तावेज़ देखें.

किसी डिवाइस पर प्लैटफ़ॉर्म चालू करना

उपयोगकर्ताओं को डिवाइस की सेटिंग > पासवर्ड और खाते > आपका प्लैटफ़ॉर्म > चालू या बंद करें के ज़रिए, प्लैटफ़ॉर्म को चालू करना होगा.

fun createSettingsPendingIntent(): PendingIntent