メインコンテンツへスキップ
iOS

ASWebAuthenticationSessionを使用してiOSアプリにHuman Token Journeyを統合します。

Markdown

ASWebAuthenticationSessionは、システム管理のブラウザでHuman Token Journeyを起動します。ジャーニーが完了すると、登録されたURLスキームを介してアプリにセッションが戻ります。

前提条件​

  • iOS 13以降
  • Xcode 14+
  • AuthenticationServicesフレームワーク(組み込み)
  • アプリ固有のURLスキーム(例:myapp)

ステップ 1:URLスキームを定義する​

一意のスキームを選択します(例:myapp)。プロセス作成時にcallbackUriとして使用されます:

callbackUri: myapp://callback

ステップ 2:プレゼンテーションコンテキストプロバイダーを作成する​

import AuthenticationServices
import UIKit

class UnicoAuthenticationController: NSObject, ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first else {
return ASPresentationAnchor()
}
return window
}
}

ステップ 3:セッションマネージャーを作成する​

import AuthenticationServices

class AuthenticationSessionManager {
static let shared = AuthenticationSessionManager()
private var session: ASWebAuthenticationSession?
private let contextProvider = UnicoAuthenticationController()

func start(url: URL, completion: @escaping (String?) -> Void) {
let newSession = ASWebAuthenticationSession(
url: url,
callbackURLScheme: "myapp"
) { callbackURL, error in
self.session = nil
if let callbackURL = callbackURL {
let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)
let processId = components?.queryItems?.first(where: { $0.name == "id" })?.value
completion(processId)
} else {
completion(nil)
}
}
newSession.presentationContextProvider = contextProvider
newSession.prefersEphemeralWebBrowserSession = true
newSession.start()
session = newSession
}
}

ステップ 4:ジャーニーを開始する​

guard let url = URL(string: processLink) else { return }

AuthenticationSessionManager.shared.start(url: url) { processId in
if let processId = processId {
// Journey completed — send processId to your backend via Get Process
} else {
// User canceled the session
}
}
情報

callbackURLSchemeパラメーターはスキーム名のみ(myapp)を受け取り、://は含みません。

ファイルの概要​

ファイル目的
UnicoAuthenticationController.swiftプレゼンテーションコンテキストプロバイダー
セッションマネージャー(ビューまたはサービス)ASWebAuthenticationSessionのライフサイクル