iOS Moya實現(xiàn)OAuth請求的方法
0. 起源
開放授權(quán)(OAuth)是一個開放標(biāo)準(zhǔn),允許用戶讓第三方應(yīng)用訪問該用戶在某一網(wǎng)站上存儲的私密的資源(如照片,視頻,聯(lián)系人列表),而無需將用戶名和密碼提供給第三方應(yīng)用。
而作為第三方軟件,為用戶提供 OAuth 登錄是更好的選擇,可以有效打消用戶對于個人賬戶密碼泄露的顧慮,同時也能有效避免用戶反復(fù)登錄,進(jìn)而增加用戶的舒適度,提高用戶粘性。
1. 環(huán)境
項目使用 MVVM 架構(gòu),引入了 Rx 全家桶,網(wǎng)絡(luò)請求框架使用了 Moya ,以及處理 Oauth 相關(guān)的庫 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 的底層網(wǎng)絡(luò)請求實現(xiàn)是基于 Alamofire,因此我們可以參照 OAuth2 提供的說明文檔 Alamofire 4 · p2/OAuth2 Wiki · GitHub 完成相關(guān)配置,關(guān)鍵代碼如下:
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
}
進(jìn)而生成帶 OAuth 的 provider:
fileprivate lazy var provider: MoyaProvider = {
return MoyaProvider<API>(manager: self.getManager(),
plugins: [NetworkLoggerPlugin()])
}()
使用
使用生成的 provider 發(fā)送請求即可,此時 Moya 可自動處理 OAuth 認(rèn)證信息。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IOS 使用Block二次封裝AFNetworking 3.0詳解
這篇文章主要介紹了IOS 使用Block二次封裝AFNetworking 3.0詳解的相關(guān)資料,需要的朋友可以參考下2017-02-02
Swift實現(xiàn)iOS應(yīng)用中短信驗證碼倒計時功能的實例分享
這篇文章主要介紹了Swift實現(xiàn)iOS應(yīng)用中短信驗證碼倒計時功能的實例分享,開啟和關(guān)閉倒計時功能的步驟實現(xiàn)比較關(guān)鍵,需要的朋友可以參考下2016-04-04
iOS中的多線程如何按設(shè)定順序去執(zhí)行任務(wù)詳解
多線程相信大家或多或少都有所了解吧,下面這篇文章主要給大家介紹了關(guān)于iOS中多線程如何按設(shè)定順序去執(zhí)行任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對各位iOS開發(fā)者們的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-12-12

