本文說明如何整合 Credential Manager API 與使用 WebView 的 Android 應用程式。1.12.0 以上版本的 android.webkit.WebView 程式庫原生支援 Credential Manager。
必要條件
如要在 WebView 中使用 Credential Manager,請將下列依附元件新增至應用程式模組的建構指令碼:
dependencies {
implementation("androidx.credentials:credentials:1.6.0-beta02")
implementation("androidx.credentials:credentials-play-services-auth:1.6.0-beta02")
implementation("androidx.webkit:webkit:1.14.0")
}
您也需要使用數位資產連結,將應用程式與應用程式擁有的網站建立關聯。詳情請參閱新增數位資產連結。
使用 WebKit 程式庫
如要使用 WebKit 程式庫,請先檢查功能支援情況,然後呼叫 setWebAuthenticationSupport() 啟用支援:
class WebViewActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val url = "https://passkeys-codelab.glitch.me/"
AndroidView(
factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
webViewClient = WebViewClientImpl()
}
},
update = { webView ->
run {
webView.loadUrl(url)
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_AUTHENTICATION)) {
WebSettingsCompat.setWebAuthenticationSupport(
webView.settings,
WebSettingsCompat.WEB_AUTHENTICATION_SUPPORT_FOR_APP,
)
// Check if getWebauthenticationSupport may have been disabled by the WebView.
Log.e(
"WebViewPasskeyDemo",
"getWebAuthenticationSupport result: " + WebSettingsCompat.getWebAuthenticationSupport(
webView.settings
),
)
} else {
Log.e("WebViewPasskeyDemo", "WebView does not support passkeys.")
}
}
},
)
}
}
}
網路整合
如要瞭解如何建構網路整合程序,請參閱「為無密碼登入建立密碼金鑰」。您也可以參考示範網站來源。
測試與部署
在受監控的環境中完整測試整個流程,確認 Android 應用程式、網頁和後端之間能夠順利通訊。
將整合後的解決方案部署至實際工作環境,確認後端可處理傳入的註冊和驗證要求。後端程式碼應產生註冊 (create) 和驗證 (get) 程序的初始 JSON,並處理從網頁接收的回應驗證作業。
確認實作方式是否與使用者體驗建議相符。