Swiftpack.co - Package - OAuthSwift/OAuthSwift

OAuthSwift

OAuthSwift

Swift based OAuth library for iOS and macOS.

Support OAuth1.0, OAuth2.0

Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, Linkedin, Dropbox, Dribbble, Salesforce, BitBucket, GoogleDrive, Smugmug, Intuit, Zaim, Tumblr, Slack, Uber, Gitter, Facebook, Spotify, Typetalk, SoundCloud, Twitch, etc

Installation

OAuthSwift is packaged as a Swift framework. Currently this is the simplest way to add it to your app:

  • Drag OAuthSwift.xcodeproj to your project in the Project Navigator.
  • Select your project and then your app target. Open the Build Phases panel.
  • Expand the Target Dependencies group, and add OAuthSwift framework.
  • import OAuthSwift whenever you want to use OAuthSwift.

Support Carthage

  • Install Carthage (https://github.com/Carthage/Carthage)
  • Create Cartfile file
github "OAuthSwift/OAuthSwift" ~> 2.0.0
  • Run carthage update.
  • On your application targets’ “General” settings tab, in the “Embedded Binaries” section, drag and drop OAuthSwift.framework from the Carthage/Build/iOS folder on disk.

Support CocoaPods

  • Podfile
platform :ios, '10.0'
use_frameworks!

pod 'OAuthSwift', '~> 2.0.0'

Swift Package Manager Support

import PackageDescription

let package = Package(
    name: "MyApp",
    dependencies: [
        .package(name: "OAuthSwift", url: "https://github.com/OAuthSwift/OAuthSwift.git", .upToNextMajor(from: "2.1.0"))
    ]
)

Old versions

Swift 3

Use the swift3 branch, or the tag 1.1.2 on main branch

Swift 4

Use the tag 1.2.0 on main branch

Objective-C

Use the tag 1.4.1 on main branch

How to

Setting URL Schemes

In info tab of your target Image Replace oauth-swift by your application name

Handle URL in AppDelegate

  • On iOS implement UIApplicationDelegate method
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey  : Any] = [:]) -> Bool {
  if url.host == "oauth-callback" {
    OAuthSwift.handle(url: url)
  }
  return true
}
  • On iOS 13, UIKit will notify UISceneDelegate instead of UIApplicationDelegate.
  • Implement UISceneDelegate method
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {
            return
        }
        if url.host == "oauth-callback" {
            OAuthSwift.handle(url: url)
        }
}

:warning: Any other application may try to open a URL with your url scheme. So you can check the source application, for instance for safari controller :

if options[.sourceApplication] as? String == "com.apple.SafariViewService" {
  • On macOS you must register a handler on NSAppleEventManager for event type kAEGetURL (see demo code)
func applicationDidFinishLaunching(_ aNotification: NSNotification) {
    NSAppleEventManager.shared().setEventHandler(self, andSelector:#selector(AppDelegate.handleGetURL(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func handleGetURL(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
    if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) {
        OAuthSwift.handle(url: url)
    }
}

Authorize with OAuth1.0

// create an instance and retain it
oauthswift = OAuth1Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    requestTokenUrl: "https://api.twitter.com/oauth/request_token",
    authorizeUrl:    "https://api.twitter.com/oauth/authorize",
    accessTokenUrl:  "https://api.twitter.com/oauth/access_token"
)
// authorize
let handle = oauthswift.authorize(
    withCallbackURL: "oauth-swift://oauth-callback/twitter") { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      print(credential.oauthTokenSecret)
      print(parameters["user_id"])
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }             
}

OAuth1 without authorization

No urls to specify here

// create an instance and retain it
oauthswift = OAuth1Swift(
    consumerKey:    "********",
    consumerSecret: "********"
)
// do your HTTP request without authorize
oauthswift.client.get("https://api.example.com/foo/bar") { result in
    switch result {
    case .success(let response):
        //....
    case .failure(let error):
        //...
    }
}

Authorize with OAuth2.0

// create an instance and retain it
oauthswift = OAuth2Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    authorizeUrl:   "https://api.instagram.com/oauth/authorize",
    responseType:   "token"
)
let handle = oauthswift.authorize(
    withCallbackURL: "oauth-swift://oauth-callback/instagram",
    scope: "likes+comments", state:"INSTAGRAM") { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }
}

Authorize with OAuth2.0 and proof key flow (PKCE)

// create an instance and retain it
oauthswift = OAuth2Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    authorizeUrl: "https://server.com/oauth/authorize",
    responseType: "code"
)
oauthswift.accessTokenBasicAuthentification = true

let codeVerifier = base64url("abcd...")
let codeChallenge = codeChallenge(for: codeVerifier)

let handle = oauthswift.authorize(
    withCallbackURL: "myApp://callback/",
    scope: "requestedScope", 
    state:"State01",
    codeChallenge: codeChallenge,
    codeChallengeMethod: "S256",
    codeVerifier: codeVerifier) { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }
}

See demo for more examples

Handle authorize URL

The authorize URL allows the user to connect to a provider and give access to your application.

By default this URL is opened into the external web browser (ie. safari), but apple does not allow it for app-store iOS applications.

To change this behavior you must set an OAuthSwiftURLHandlerType, simple protocol to handle an URL

oauthswift.authorizeURLHandler = ..

For instance you can embed a web view into your application by providing a controller that displays a web view (UIWebView, WKWebView). Then this controller must implement OAuthSwiftURLHandlerType to load the URL into the web view

func handle(_ url: NSURL) {
  let req = URLRequest(URL: targetURL)
  self.webView.loadRequest(req)
  ...

and present the view (present(viewController, performSegue(withIdentifier:, ...) You can extend OAuthWebViewController for a default implementation of view presentation and dismiss

Use the SFSafariViewController (iOS9)

A default implementation of OAuthSwiftURLHandlerType is provided using the SFSafariViewController, with automatic view dismiss.

oauthswift.authorizeURLHandler = SafariURLHandler(viewController: self, oauthSwift: oauthswift)

Of course you can create your own class or customize the controller by setting the variable SafariURLHandler#factory.

Make signed request

Just call HTTP functions of oauthswift.client

oauthswift.client.get("https://api.linkedin.com/v1/people/~") { result in
    switch result {
    case .success(let response):
        let dataString = response.string
        print(dataString)
    case .failure(let error):
        print(error)
    }
}
// same with request method
oauthswift.client.request("https://api.linkedin.com/v1/people/~", .GET,
      parameters: [:], headers: [:],
      completionHandler: { ...

See more examples in the demo application: ViewController.swift

OAuth provider pages

Images

Image Image Image

Contributing

See CONTRIBUTING.md

Add a new service in demo app

Integration

OAuthSwift could be used with others frameworks

You can sign Alamofire request with OAuthSwiftAlamofire

To achieve great asynchronous code you can use one of these integration frameworks

License

OAuthSwift is available under the MIT license. See the LICENSE file for more info.

License Platform Language Cocoapod Carthage compatible Build Status

Github

link
Stars: 2625

Used By

Total: 0

Releases

- 2020-05-02 19:52:51

Some fix for tvOS compatibility

- 2020-04-30 17:10:49

2.0.1 SwiftPM - 2019-11-01 22:37:55

  • Fix swiftPM
  • Fix build extension @shadyoak
  • Change on lock mecanism @flangel

2.1.0 `Catalyst` - 2019-11-01 22:35:03

  • Support of macCatalyst, add ASWebAuthenticationURLHandler @nrivard
  • Fix some deprecation warnings

demo app

  • add twitch to demo app @coolioxlr
  • add ASWebAuthenticationURLHandler to demo app
  • demo app tested with macCatalyst
  • better with dark mode
  • use WKWebView instead of deprecated UIWebView

2.0.0`Result` - 2019-06-10 20:57:05

Big breaking change on callback closure!

Result type is now used to merge the success and failure closure into one.

oauthswift.authorize(..) { result in
    switch result {
    case .success(let (credential, response, parameters)):
      // do something
    case .failure(let error):
      // do something
    }  
}
oauthswift.client.get(...) { result in
    switch result {
    case .success(let response):
        // do something
    case .failure(let error):
        // do something
    }
}

You can use the previous version 1.4.x if you do not want to upgrade your code

- 2019-06-10 20:08:04

Revert change for #522

  • no need to retain authorizeURLHandler
  • but to break memory cycle you can call .weak() on your OAuthSwiftURLHandlerType

- 2019-06-10 19:34:39

swift 5 @alex-taffe Add Safari views for iOS 11+ @SMillerDev

Fix #492 : option useRFC3986ToEncodeToken on OAutSwift1 Fix #509 : change on error domain, no more use of URLErrorDomain Fix #522 : now authorizeURLHandler attribute are "weak" to break cycle -> you must retain your object elsewhere to not be deallocated

- 2017-06-04 10:33:08

New

  • add encodeCallbackURL to oauth 2 to URL encore callback URL. Seems to be needed for some services issue #339, pr #325
  • in SafariURLHandler presentViewControllerAnimated variable added by @felipeflorencio
  • Optionally add callback URL to authorize URL using addCallbackURLToAuthorizeURL field of OAuth1Swift , as requested by PR #373
  • add NounProject and Digu to demo app

Change

  • swift 3.1 warning @patricks @hiragram
  • restore OAuth1Swift init without URL parameters @josephquigley
  • Allow changing grand type of device token authorisation Fix #377
  • Add parameters parameter to renewAccessToken @wesley-dynamicowl

Fix

  • Do not send oauth_verifier query parameter if not necessary ie. if allowMissingOAuthVerifier=true, Fix #334
  • Fix a crash when encoding credentials in a test target @eunikolsky

- 2017-02-26 10:36:46

Change

  • Now success Handler return a OAuthSwiftResponse, which contains the Data, the HTTPURLResponse and URLRequest
    • On this object you can get decoded json object, string value, ...
    • You can extends OAuthSwiftResponse to use some JSON decoded like SwiftyJSON or any object mapper
  • If there is some problem to encode URL with OAuth2, "handle" is not returned (request is cancelled)

New

  • OAuthSwiftError implement CustomNSError protocol
  • Ability to specify body data for POST request
  • Add wordpress in demo

Fix

  • Fix multipart request with some parameter #287 @ktakayama
  • Fix OAuthSwiftCredential.Version init(:) error @bzmario

- 2016-11-05 17:01:04

In success handler/closure an OAuthSwiftResponse object is now returned instead of multiple objects (data and http response)

oauthswift.client.get("an url",
      success: { response in
           let data = response.data // response.string for utf8 decoded string from data
      },
...

You can extends OAuthSwiftResponse to return a decoded object by reading JSON for instance

You can also get the URLRequest send to the server into this OAuthSwiftResponse object


Backward compatibility with Objective C work with prefixed objc_ functions

- 2016-10-06 12:50:50

Update to swift 3

  • functions renamed (ex: authorizeWithCallbackURL( -> authorize(withCallbackURL:)
  • error in callback is typed OAuthSwiftError
  • variable with _ renamed (ex: oauthSwift.client.credential.oauth_token-> oauthSwift.client.credential.oauthToken)
  • add some type alias (ex: OAuthSwift.Headers , OAuthSwift.Parameters)
  • ...

Take a look to also updated project OAuthSwiftAlamofire if you want to use Alamofire to make request

- 2016-07-28 20:42:13

  • See Milestone for bug fix
  • many change from @FGoessler PR #219
    • fix memory leak
    • allow to cancel request
    • ..
  • Fix and customisation on provided web view controller presentation and dismissal
  • Demo app have now a form to choose url handler and fill key and secret
  • add SoundCloud to OAuthSwiftDemo @satoshin2071

:warning: If you update and use SafariURLHandler, you will have a compilation issue: SafariURLHandlerinit now take an OAuthSwiftobject as parameter

- 2016-04-06 07:53:03

Fix

  • on oauth1 signature (@danielbmarques)
  • use of oauthswift into app extension
  • request that start with &

Change

  • swift 2.2 warnings (@lyptt)
  • allow to refresh token for oauth2 (@fabiomassimo )
  • add an enum OAuthSwiftErrorCode (@fabiomassimo )
  • added a method to OAuthSwiftClient to perform requests via NSURLRequest objects (@FGoessler)
  • allow to cancel OAuthSwiftHTTPRequest (@FGoessler)

Other

  • added to demo Goodreads, Typetalk, Buffer, Trello

- 2016-02-23 10:10:51

Fix

  • fix fatal error if no access_token_url defined but needed
  • do not silently do nothing if failed to create authorize url
  • encode authorize url (fix scope with space)
  • remove percent encoding from oauth_token

Change

  • Add method removeCallbackNotificationObserver to release the observer (which wait on callback url called by website provider)
  • Add "Response-Body" when request failed (@lyptt)
  • oauth_verifier now public (@itchingpixels)
  • Add 'state' check when receiving code #182
  • Allow to send oauth parameter in URL instead of header (Withings, @jdrevet)

Other

  • add to demo 500px, hatena
  • document and use in demo iOS9 UIApplicationDelegate new method to handle url

- 2015-12-27 14:18:01

Fix

  • JSON parsing to get access token when there is one parameter with only number
  • Presentation of OAuthWebViewController by choosing the good parent view controller, not only the root one

Change

  • Add parameters to OAuth1 callback #81(@quangbuule #152)
  • Add WatchOS support #135 (as proof of concept, you must do find a way to handle authorisation URL, maybe open on iOS)
  • Allow to change dispatch queue used by HTTP request (default: main queue)
  • Factorise code between OAuth1Swift & OAuthSwift2 :

After updating you must edit your code:

  • For OAuth1 you must change the callback credential, response in by credential, response, parameters in or credential, response, _ in
  • :warning: response into callback could now be nil
  • OAuth1Swift.handleOpenURL(url:) & OAuth2Swift.handleOpenURL(url:) are replaced by OAuthSwift.handleOpenURL(url:)

If you don't want to edit your code, do not update OAuthSwift. You can with carthage and cocoapod for instance use "~> 0.4.8"

- 2015-11-30 12:07:59

New

  • Add TVOS support (as proof of concept, webview not allowed on TVOS)
  • Add SafariURLHandler to handle URL into a SFSafariViewController (iOS9)
  • Add Gitter & Facebook service into demo

Fix

  • initialisation from stored token by setting OAuth version at object init
  • #129 Allow to use in application extension
  • #142 error on signature if url contains query parameters (@pculligan)
  • #140 some errors if service return no data or no token (@pculligan, @srna, @mikeMTOL)
  • #139 header with basic password (for instance for FitBit OAuth2)
  • #80 allow to specify header to POST Json data and fix OAuth1 signature
  • No OAuth2 Authorization header if no token (#151 @gufo)

Internal

  • Add unit tests
  • Add contributing guide
  • Merge OSX and iOS demo code
  • Change the way to configure demo app consumer key and secret Demo-application