iOS Moya實現OAuth請求的方法

這篇文章主要介紹了iOS Moya實現OAuth請求的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

0. 起源

開放授權(OAuth)是一個開放標準,允許用戶讓第三方應用訪問該用戶在某一網站上存儲的私密的資源(如照片,視頻,聯繫人列表),而無需將用戶名和密碼提供給第三方應用。

而作爲第三方軟件,爲用戶提供 OAuth 登錄是更好的選擇,可以有效打消用戶對於個人賬戶密碼泄露的顧慮,同時也能有效避免用戶反覆登錄,進而增加用戶的舒適度,提高用戶粘性。

1. 環境

項目使用 MVVM 架構,引入了 Rx 全家桶,網絡請求框架使用了 Moya ,以及處理 Oauth 相關的庫 OAuth2

2. OAuth2 部分

參閱 OAuth2 庫的 README ,完成 OAuth 的信息配置:

let oauth2 = OAuth2CodeGrant(settings: [
  "client_id": "my_swift_app",
  "client_secret": "C7447242",
  "authorize_uri": "https://github.com/login/oauth/authorize",
  "token_uri": "https://github.com/login/oauth/access_token",
  "redirect_uris": ["myapp://oauth/callback"],
  "scope": "user repo:status",
  "secret_in_body": true,
  "keychain": false,
] as OAuth2JSON)

同時因爲 Moya 的底層網絡請求實現是基於 Alamofire,因此我們可以參照 OAuth2 提供的說明文檔 Alamofire 4 · p2/OAuth2 Wiki · GitHub 完成相關配置,關鍵代碼如下:

import Foundation
import OAuth2
import Alamofire


class OAuth2RetryHandler: RequestRetrier, RequestAdapter {
  
  let loader: OAuth2DataLoader
  
  init(oauth2: OAuth2) {
    loader = OAuth2DataLoader(oauth2: oauth2)
  }
  
  /// Intercept 401 and do an OAuth2 authorization.
  public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
    if let response = request.task?.response as? HTTPURLResponse, 401 == response.statusCode, let req = request.request {
      var dataRequest = OAuth2DataRequest(request: req, callback: { _ in })
      dataRequest.context = completion
      loader.enqueue(request: dataRequest)
      loader.attemptToAuthorize() { authParams, error in
        self.loader.dequeueAndApply() { req in
          if let comp = req.context as? RequestRetryCompletion {
            comp(nil != authParams, 0.0)
          }
        }
      }
    }
    else {
      completion(false, 0.0)  // not a 401, not our problem
    }
  }
  
  /// Sign the request with the access token.
  public func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    guard nil != loader.oauth2.accessToken else {
      return urlRequest
    }
    return try urlRequest.signed(with: loader.oauth2)  // "try" added in 3.0.2
  }
}

3. Moya 部分

Moya 的 provider 在初始化時可以傳入 SessionManager ,因此參照文檔,可以先使用 OAuth2 生成一個特定的 SessionManager :

func getManager() -> SessionManager {

    let oauth2 = OAuth2CodeGrant(settings: [
      "client_id": "my_swift_app",
      "client_secret": "C7447242",
      "authorize_uri": "https://github.com/login/oauth/authorize",
      "token_uri": "https://github.com/login/oauth/access_token",
      "redirect_uris": ["myapp://oauth/callback"],
      "scope": "user repo:status",
      "secret_in_body": true,
      "keychain": false,
      ] as OAuth2JSON)

    let sessionManager = SessionManager()
    let oauthHandler = OAuth2Handler(oauth2: oauth2)
    sessionManager.adapter = oauthHandler
    sessionManager.retrier = oauthHandler
    return sessionManager
  }

進而生成帶 OAuth 的 provider:

fileprivate lazy var provider: MoyaProvider = {
  return MoyaProvider<API>(manager: self.getManager(),
              plugins: [NetworkLoggerPlugin()])
}()

使用

使用生成的 provider 發送請求即可,此時 Moya 可自動處理 OAuth 認證信息。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章