このガイドでは、パスキーを使用した認証の実装について説明します。 ユーザーがパスキーでログインできるようにするには、 パスキーを作成するの手順も完了する必要があります。
パスキーで認証するには、まずアプリサーバーから公開鍵を取得するために必要なオプションを取得し、Credential Manager API を呼び出して公開鍵を取得する必要があります。次に、ログイン レスポンスを適切に処理します。
概要
このガイドでは、パスキーを使用してユーザーをログインさせるためにクライアント アプリに必要な変更について説明し、アプリサーバー側の実装の概要を示します。サーバー側の統合について詳しくは、サーバーサイドの パスキー認証をご覧ください。
ユーザーのアカウントに関連付けられているすべてのパスキーとパスワードのオプションを取得する手順は次のとおりです。
- **サーバーから認証情報リクエスト オプションを取得する**: アプリから 認証サーバーにリクエストを送信して、パスキーのログイン プロセスを開始します。 サーバーから、公開鍵認証情報を取得するために必要なオプションと、一意のチャレンジを送信します。
- 公開鍵認証情報を取得するために必要なオブジェクトを作成する: サーバーから送信されたオプションを
GetPublicKeyCredentialOptionオブジェクトでラップします。 - (省略可)getCredential を準備する: Android 14 以降では、
アカウント選択ツールを表示するときのレイテンシを短縮できます。
prepareGetCredential()メソッドを使用して、getCredential()を呼び出す前に - ログインフローを開始する:
getCredential()メソッドを呼び出してユーザーをログインさせます - **レスポンスを処理する**: 可能な認証情報 レスポンスをそれぞれ処理します。
- 例外を処理する: 例外を 適切に処理するようにします。
サーバーから認証情報リクエスト オプションを取得する
公開鍵認証情報を取得するために必要なオプションと、ログイン試行ごとに一意の challenge をサーバーにリクエストします。サーバー側の実装について詳しくは、チャレンジを作成するおよび認証情報リクエスト
オプションを作成するをご覧ください。
オプションは次のようになります。
{
"challenge": "<your app challenge>",
"allowCredentials": [],
"rpId": "<your app server domain>"
}
フィールドの詳細については、パスキーでログインする に関するブログ投稿をご覧ください。
公開鍵認証情報を取得するために必要なオブジェクトを作成する
アプリで、オプションを使用して GetPublicKeyCredentialOption オブジェクトを作成します。
次の例では、requestJson はサーバーから送信されたオプションを表します。
// Get password logins from the credential provider on the user's device.
val getPasswordOption = GetPasswordOption()
// Get passkeys from the credential provider on the user's device.
val getPublicKeyCredentialOption = GetPublicKeyCredentialOption(
requestJson = requestJson
)
次に、GetPublicKeyCredentialOption を GetCredentialRequest オブジェクトでラップします。
val credentialRequest = GetCredentialRequest(
// Include all the sign-in options that your app supports.
listOf(getPasswordOption, getPublicKeyCredentialOption),
// Defines whether you prefer to use only immediately available
// credentials or hybrid credentials.
preferImmediatelyAvailableCredentials = preferImmediatelyAvailableCredentials
)
省略可: ログインのレイテンシを短縮する
Android 14 以降では、アカウント
選択ツールを表示するときのレイテンシを短縮できます。これには、prepareGetCredential() メソッドを呼び出す前に使用します
getCredential()。
prepareGetCredential() メソッドは、キャッシュされる
PrepareGetCredentialResponse オブジェクトを返します。これにより、次のステップの getCredential() メソッドで、キャッシュされたデータを使用してアカウント選択ツールを表示できます。
coroutineScope {
val response = credentialManager.prepareGetCredential(
GetCredentialRequest(
listOf(
// Include all the sign-in options that your app supports
getPublicKeyCredentialOption,
getPasswordOption
)
)
)
}
ログインフローを開始する
getCredential() メソッドを呼び出して、アカウント選択ツールをユーザーに表示します。ログインフローを開始する方法については、次のコード スニペットを参考にしてください。
// Use an activity-based context to avoid undefined system UI
// launching behavior.
val context = MutableContextWrapper(activityContext)
coroutineScope {
try {
result = credentialManager.getCredential(
// Use MutableContextWrapper to avoid memory leak during configuration changes
context = context,
request = credentialRequest
)
handleSignIn(result)
} catch (e: GetCredentialException) {
// Handle failure
}
}
レスポンスを処理する
さまざまな種類の認証情報オブジェクトを含むレスポンスを処理します。
fun handleSignIn(result: GetCredentialResponse) {
// Handle the successfully returned credential.
val credential = result.credential
when (credential) {
is PublicKeyCredential -> {
val responseJson = credential.authenticationResponseJson
// Share responseJson i.e. a GetCredentialResponse on your server to
// validate and authenticate
}
is PasswordCredential -> {
val username = credential.id
val password = credential.password
// Use id and password to send to your server to validate
// and authenticate
}
is CustomCredential -> {
// If you are also using any external sign-in libraries, parse them
// here with the utility functions provided.
if (credential.type == ExampleCustomCredential.TYPE) {
try {
val ExampleCustomCredential =
ExampleCustomCredential.createFrom(credential.data)
// Extract the required credentials and complete the authentication as per
// the federated sign in or any external sign in library flow
} catch (e: ExampleCustomCredential.ExampleCustomCredentialParsingException) {
// Unlikely to happen. If it does, you likely need to update the dependency
// version of your external sign-in library.
Log.e(TAG, "Failed to parse an ExampleCustomCredential", e)
}
} else {
// Catch any unrecognized custom credential type here.
Log.e(TAG, "Unexpected type of credential")
}
}
else -> {
// Catch any unrecognized credential type here.
Log.e(TAG, "Unexpected type of credential")
}
}
}
認証から返される PublicKeyCredential は、基本的に次のように構造化された署名付きアサーションです。
{
"id": "<credential ID>",
"type": "public-key",
"rawId": "<raw credential ID>",
"response": {
"clientDataJSON": "<signed client data containing challenge>",
"authenticatorData": "<authenticator metadata>",
"signature": "<digital signature to be verified>",
"userHandle": "<user ID from credential registration>"
}
}
サーバーで認証情報を検証する必要があります。詳しくは、ユーザーを検証して ログインさせるをご覧ください。
例外を処理する
GetCredentialException のすべてのサブクラス例外を処理する必要があります。
各例外の処理方法については、トラブルシューティング ガイドをご覧ください。
coroutineScope {
try {
result = credentialManager.getCredential(
context = activityContext,
request = credentialRequest
)
} catch (e: GetCredentialException) {
Log.e("CredentialManager", "No credential available", e)
}
}