AlamofireOAuth1 0.1.0

AlamofireOAuth1 0.1.0

Cencen Zheng 维护。



 
依赖
Alamofire>= 0
KeychainAccess>= 0
 

  • 作者
  • Cencen Zheng

AlamofireOAuth1

CI Status Version License Platform

AlamofireOAuth1 是一个基于 Alamofire 的 OAuth1 库,用于 iOS。

原因

基于 Swift 的 OAuth1 库选择不多,虽然 OAuthSwift 可能是最好的(也是唯一的),但它有点庞大(如果您只需要 OAuth1 或 OAuth 2)。此外,您必须调用 oauthswift.client 来执行签名请求(而您已经有了基于 Alamofire 的 HTTPClient)。

用法

获取访问令牌

// create an instance directly
let oauth1 = OAuth1(key: "********",
secret: "********",
requestTokenUrl: "http://fanfou.com/oauth/request_token",
authorizeUrl: "http://fanfou.com/oauth/authorize",
accessTokenUrl: "http://fanfou.com/oauth/access_token",
callbackUrl: "alamofire-oauth1://callback")

// or instantiate with OAuth1Settings(see OAuth1Settings.swift.example)
let oauth1 = OAuth1()

// by default the authorized URL is opened in Safari
// you can make a SafariOpenURLHandler to use the SFSafariViewController
// the idea is inspired by OAuthSwift
let handler = SafariOpenURLHandler(viewController: self)
oauth1.authorizeURLHandler = handler

// fetch access token
oauth1.fetchAccessToken(accessMethod: .get, successHandler: { (accessToken) in
// handle with accessToken
}, failureHandler: errorHandler)

不要忘记注册您的应用程序,以便从自定义 URL 规划启动。在这种情况下,回调 URL 是 alamofire-oauth1://callback

使用 handleCallback 在 iOS 中处理自定义 URL 规划

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if url.host == "alamofire-oauth1", url.path.contains("callback") {
OAuth1.handleCallback(callbackURL: url)
}
return true
}

保持访问令牌

// OAuth1TokenStore is built on the top of KeychainAccess

// save token
oauth1.fetchAccessToken(accessMethod: .get, successHandler: { (accessToken) in
OAuth1TokenStore.shared.saveToken(accessToken, withIdentifier: self.tokenId)
}, failureHandler: errorHandler)

// retrieve token
let accessToken: OAuth1Token = try OAuth1TokenStore.shared.retrieveCurrentToken(withIdentifier: tokenId)

创建验证请求

RequestAdapter是Alamofire 4的新功能。它允许在创建之前对在SessionManager上执行的每个Request进行检查和调整,这使得轻松向请求添加Authorization头变得简单。

  • 使用APIClient进行授权和请求
// create a Router 
// see Routing Requests: https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests
enum Router: URLRequestConvertible {
case fanfou
case twitter

func asURLRequest() throws -> URLRequest {
    return ...
}
}
// APClient has adopted RequestAdapter. 

func testTwitter() {
    let oauth1 = OAuth1(key: "YOUR-TWITTER-CONSUMER-KEY",
    secret: "YOUR-TWITTER-CONSUMER-SECRET",
    requestTokenUrl: "https://api.twitter.com/oauth/request_token",
    authorizeUrl: "https://api.twitter.com/oauth/authorize",
    accessTokenUrl: "https://api.twitter.com/oauth/access_token",
    callbackUrl: "https://alamofireoauth1redirect.herokuapp.com/")
    let client = APIClient(with: oauth1)
    client.authorize(with: SafariURLOpener(viewController: self)) {
        client.request(Router.twitter).validate().responseJSON(completionHandler: { (response) in
            debugPrint(response.result)
        })
    }
}
  • 使用adaptRequest:withAccessToken函数实现您的适配器
open func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    let accessToken = try OAuth1TokenStore.shared.retrieveCurrentToken(withIdentifier: tokenId)
    return try oauth1.adaptRequest(urlRequest, withAccessToken: accessToken)
}

示例

要运行示例项目,首先克隆仓库,然后从示例目录运行pod install。在ViewController.swift中展示了与Twitter和饭否进行身份验证的过程。

安装

AlamofireOAuth1可通过CocoaPods获得。要安装它,只需将以下行添加到您的Podfile中

pod 'AlamofireOAuth1'

许可证

AlamofireOAuth1在MIT许可证下提供。有关更多信息,请参阅LICENSE文件。