iOS Moya实现OAuth请求的方法

2025-05-29 0 92

0. 起源

开放授权(OAuth)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。

而作为第三方软件,为用户提供 OAuth 登录是更好的选择,可以有效打消用户对于个人账户密码泄露的顾虑,同时也能有效避免用户反复登录,进而增加用户的舒适度,提高用户粘性。

1. 环境

项目使用 MVVM 架构,引入了 Rx 全家桶,网络请求框架使用了 Moya ,以及处理 Oauth 相关的库 OAuth2 。

2. OAuth2 部分

参阅 OAuth2 库的 README ,完成 OAuth 的信息配置:

?

1

2

3

4

5

6

7

8

9

10
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 完成相关配置,关键代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40
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 :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
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:

?

1

2

3

4
fileprivate lazy var provider: MoyaProvider = {

return MoyaProvider<API>(manager: self.getManager(),

plugins: [NetworkLoggerPlugin()])

}()

使用

使用生成的 provider 发送请求即可,此时 Moya 可自动处理 OAuth 认证信息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS Moya实现OAuth请求的方法 https://www.kuaiidc.com/89017.html

相关文章

发表评论
暂无评论