Git Product home page Git Product logo

swiftyoauth's Introduction

Travis Status CocoaPods compatible Carthage compatible

SwiftyOAuth is a small OAuth library with a built-in set of providers and a nice API to add your owns.

let instagram: Provider = .Instagram(clientID: "***", redirectURL: "foo://callback")

instagram.authorize { result in
    print(result) // Success(Token(accessToken: "abc123"))
}

UsageProvidersInstallationLicense

Usage

Provider

Provider.swift

Step 1: Create a provider

Initialize a provider with the custom URL scheme that you defined:

// Provider using the server-side (explicit) flow

let provider = Provider(
    clientID:     "***",
    clientSecret: "***",
    authorizeURL: "https://example.com/authorize",
    tokenURL:     "https://example.com/authorize/token",
    redirectURL:  "foo://callback"
)

// Provider using the client-side (implicit) flow

let provider = Provider(
    clientID:     "***",
    authorizeURL: "https://example.com/authorize",
    redirectURL:  "foo://callback"
)

// Provider using the client-credentials flow

let provider = Provider(
    clientID:     "***",
    clientSecret: "***"
)

Alternatively, you can use one of the built-in providers:

let github = .GitHub(
    clientID:     "***",
    clientSecret: "***",
    redirectURL:  "foo://callback"
)

Optionally set the state and scopes properties:

github.state  = "asdfjkl;" // An random string used to protect against CSRF attacks.
github.scopes = ["user", "repo"]

Use a WKWebView if the provider doesn't support custom URL schemes as redirect URLs.

let provider = Provider(
    clientID:     "***",
    clientSecret: "***",
    authorizeURL: "https://example.com/authorize",
    tokenURL:     "https://example.com/authorize/token",
    redirectURL:  "https://an-arbitrary-redirect-url/redirect"
)

provider.useWebView = true

Define additional parameters for the authorization request or the token request with additionalAuthRequestParams and additionalTokenRequestParams respectively:

github.additionalAuthRequestParams["allow_signup"] = "false"
Step 2: Handle the incoming requests

Handle the incoming requests in your AppDelegate:

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    github.handleURL(url, options: options)

    return true
}
Step 3: Ask for authorization

Finally, ask for authorization. SwiftyOAuth will either present a SFSafariViewController (iOS 9) or open mobile safari.

github.authorize { (result: Result<Token, Error>) -> Void in
    switch result {
    case .Success(let token): print(token)
    case .Failure(let error): print(error)
    }
}

If the provider provides an expirable token, you may want to refresh it.

let uber: Provider = .Uber(
    clientID: "***",
    clientSecret: "***",
    redirectURL: "foo://callback/uber"
)

// uber.token!.isExpired => true

uber.refreshToken { result in
    switch result {
    case .Success(let token): print(token)
    case .Failure(let error): print(error)
    }
}

Token

Token.swift

The access_token, token_type, scopes, and informations related to the expiration are available as Token properties:

token.accessToken // abc123
token.tokenType   // .Bearer
token.scopes      // ["user", "repo"]

token.expiresIn // 123
token.isExpired // false
token.isValid   // true

Additionally, you can access all the token data via the dictionary property:

token.dictionary // ["access_token": "abc123", "token_type": "bearer", "scope": "user repo"]

Token Store

Every Token is stored and retrieved through an object that conforms to the TokenStore protocol.

The library currently supports following TokenStores:

  • NSUserDefaults: the default Token Store. Information are saved locally and, if properly initialized, to your App Group.
  • NSUbiquitousKeyValueStore: the information are saved in the iCloud Key Value Store. Before you use this Token Store make sure your project has been properly configured as described here.

Error

Error.swift

Error is a enum that conforms to the ErrorType protocol.

  • Cancel The user cancelled the authorization process by closing the web browser window.

  • ApplicationSuspended The OAuth application you set up has been suspended.

  • RedirectURIMismatch The provided redirectURL that doesn't match what you've registered with your application.

  • AccessDenied The user rejects access to your application.

  • InvalidClient The clientID and or clientSecret you passed are incorrect.

  • InvalidGrant The verification code you passed is incorrect, expired, or doesn't match what you received in the first request for authorization.

  • Other The application emitted a response in the form of {"error": "xxx", "error_description": "yyy"} but SwiftyOAuth doesn't have a enum for it. The data is available in the associated values.

  • Unknown The application emitted a response that is neither in the form of a success one ({"access_token": "xxx"...}) nor in the form of a failure one ({"error": "xxx"...}). The data is available in the associated value.

  • NSError An error triggered when making network requests or parsing JSON. The data is available in the associated value.

Providers

Providers/

Check the wiki for more informations!

Installation

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate SwiftyOAuth into your Xcode project using Carthage, specify it in your Cartfile:

github "delba/SwiftyOAuth" >= 0.3

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

You can install it with the following command:

$ gem install cocoapods

To integrate SwiftyOAuth into your Xcode project using CocoaPods, specify it in your Podfile:

use_frameworks!

pod 'SwiftyOAuth', '~> 0.3'

License

Copyright (c) 2016 Damien (http://delba.io)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

swiftyoauth's People

Contributors

delba avatar fabiomassimo avatar johannwilfling avatar

Watchers

James Cloos avatar Lerist avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.