如何通過 ASWebAuthenticationSession 獲取身份驗證 Code 碼
本文轉載自微信公眾號「網(wǎng)羅開發(fā)」,作者展菲。轉載本文請聯(lián)系網(wǎng)羅開發(fā)公眾號。
1. 前言
項目中需要實現(xiàn) GitHub、Google、Apple 登錄,實現(xiàn)第三方登錄方案有 3 種:
- 集成第三方一鍵登錄
- 分別集成 GitHub、Google、Apple 登錄 SDK
- 不集成 SDK 打開瀏覽器登錄
今天來講一下不集成 SDK 打開瀏覽器登錄獲取身份驗證。
這需要使用 ASWebAuthenticationSession 獲取身份驗證 code 碼。
網(wǎng)站登錄身份驗證邏輯:
一些網(wǎng)站作為一種服務提供了一種用于驗證用戶身份的安全機制。
當用戶導航到站點的身份驗證URL時,站點將向用戶提供一個表單以收集憑據(jù)。
驗證憑據(jù)后,站點通常使用自定義方案將用戶的瀏覽器重定向到指示身份驗證嘗試結果的URL。
2. 不集成 SDK 打開瀏覽器登錄
你可以通過使用指向身份驗證網(wǎng)頁的 URL 初始化實例來在應用程序中使用網(wǎng)絡身份驗證服務。
該頁面可以是你維護的頁面,也可以是由第三方操作的頁面。
通過打開瀏覽器登錄并獲取身份驗證 code 碼,可以分為兩種情況:
- 一種情況是在 App 內(nèi)部打開瀏覽器獲取身份驗證
- 一種是打開手機自帶瀏覽器獲取身份驗證
嘗試第一種情況之后 GitHub 和 Apple 均可以正常打開瀏覽器并且成功登錄拿到身份驗證碼。
但是 Google 提示在 App 內(nèi)部打開登錄頁面是不安全的,因此只能選擇第二種方式。
3. 打開手機自帶瀏覽器獲取身份驗證
3.1 配置 URL Types
建議使用 bundle id 保證唯一性。
3.2 定義全局變量
- var session: ASWebAuthenticationSession!
var session : ASWebAuthenticationSession! 需要設置為全局變量,設置為局部變量會被釋放掉導致彈框閃現(xiàn)。
3.3 獲取身份驗證 code 碼
- func oauthLogin(type: String) {
- // val GitHub、Google、SignInWithApple
- let redirectUrl = "配置的 URL Types"
- let loginURL = Configuration.shared.awsConfiguration.authURL + "/authorize" + "?identity_provider=" + type + "&redirect_uri=" + redirectUri + "&response_type=CODE&client_id=" + Configuration.shared.awsConfiguration.appClientId
- session = ASWebAuthenticationSession(url: URL(string: loginURL)!, callbackURLScheme: redirectUri) { url, error in
- if error != nil {
- return
- }
- if let responseURL = url?.absoluteString {
- let components = responseURL.components(separatedBy: "#")
- for item in components {
- if item.contains("code") {
- let tokens = item.components(separatedBy: "&")
- for token in tokens {
- if token.contains("code") {
- let idTokenInfo = token.components(separatedBy: "=")
- if idTokenInfo.count > 1 {
- let code = idTokenInfo[1]
- print("身份驗證 code 碼: \(code)")
- return
- }
- }
- }
- }
- }
- }
- }
- session.presentationContextProvider = self
- session.start()
- }
這里面有兩個參數(shù),一個是 redirectUri,一個是 loginURL。
redirectUri 就是 3.1 配置的白名單,作為頁面重定向的唯一標示。
loginURL 是由 5 塊組成:
- 服務器地址:Configuration.shared.awsConfiguration.authURL + "/authorize"
- 打開的登錄平臺:identity_provider = "GitHub"
- 重定向標識:identity_provider = "配置的 URL Types"
- 相應類型:response_type = "CODE"
- 客戶端 ID:client_id = "服務器配置"
回調(diào)中的 url 包含我們所需要的身份驗證 code 碼,需要層層解析獲取 code。
3.4 指定授權界面顯示的 window
告訴代理應該在哪個 window 展示授權界面給用戶
- #pragma mark - ASAuthorizationControllerPresentationContextProviding
- extension ViewController: ASWebAuthenticationPresentationContextProviding {
- func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
- return self.view.window ?? ASPresentationAnchor()
- }
- }