WKWebView|在应用内实现基于 Web 的认证

了解如何使用 Swift 完成 App 内基于 Web 的身份认证方式。

iOS 应用认证通常分为两种方式:

  • 原生认证(如 Sign in with Apple)
  • 基于 Web 的 OAuth 认证(如 OAuth 流程)

前者在应用内完成,后者需跳转至浏览器完成第三方服务认证(例如 Linear 移动端 App)。

在 Swift 中实现基于 Web 的认证,通常使用 ASWebAuthenticationSessionWKWebView。还有一个 SFSafariViewController 组件,但通常用于在 App 内浏览网页内容。在实践中,通常会在这些场景下选择:

  • 简单网页浏览 → SFSafariViewController(iOS9+)
  • 标准OAuth认证 → ASWebAuthenticationSession(iOS12+)
  • 复杂定制认证 → WKWebView(iOS8+)

使用 ASWebAuthenticationSession

ASWebAuthenticationSession 是 Web Authentication Session 的意思。

ASWebAuthenticationSession 是苹果最推荐的用于完成标准 OAuth 认证授权流程的方式。它专为 OAuth 等身份验证流程设计,在独立的系统进程中运行,拥有最好的安全性。

应用只能通过回调 URL 接收最终认证结果,无法访问中间过程(例如 Cookie)。

如果服务端提供标准 OAuth 服务(如GitHub、Google),最好使用ASWebAuthenticationSession。

Authenticating a User Through a Web Service | Apple Developer Documentation
Use a web authentication session to authenticate a user in your app.

使用 WKWebView

WKWebView 是 iOS 8 (2014年)引入,作为替代旧版 UIWebView 的现代 WebKit 控件。它是通用网页浏览控件,可完全自定义和控制,应用可完全访问、修改和监控所有信息(例如 Cookie)。

对于未提供标准认证 SDK 或 OAuth API 的服务,WKWebView 是唯一可行选择。

获取并持久化 Cookie

KeyChain 通常用于存储密码,不推荐用于存储 Cookie。