Code Monkey home page Code Monkey logo

oauth2's Introduction

OAuth2

OAuth2 frameworks for OS X and iOS written in Swift.

The code in this repo requires Xcode 6, the built framework can be used on OS X 10.9 or iOS 8 and later. To use on iOS 7 you'll have to include the source files in your main project. Note that it's possible to run embedded frameworks in iOS 7 with some tricks, however you will not be able to submit such an App to the App Store. Supported OAuth2 flows are the code grant (response_type=code) and the implicit grant (response_type=token).

Since the Swift language is constantly evolving I am adding tags that mark which revision should work with which Xcode version.

Usage

For a typical code grant flow you want to perform the following steps. The steps for other flows are mostly the same short of instantiating a different subclass and using different client settings. If you need to provide additional parameters to the authorize URL take a look at authorizeURLWithRedirect(redirect:scope:params:).

  1. Create a settings dictionary.

    let settings = [
        "client_id": "my_swift_app",
        "client_secret": "C7447242-A0CF-47C5-BAC7-B38BA91970A9",
        "authorize_uri": "https://authorize.smartplatforms.org/authorize",
        "token_uri": "https://authorize.smartplatforms.org/token",
        "scope": "profile email",
        "redirect_uris": ["myapp://oauth/callback"],   // don't forget to register this scheme
    ]
  2. Create an OAuth2CodeGrant instance, optionally setting the onAuthorize and onFailure closures to keep informed about the status.

    let oauth = OAuth2CodeGrant(settings: settings)
    oauth.viewTitle = "My Service"      // optional
    oauth.onAuthorize = { parameters in
        println("Did authorize with parameters: \(parameters)")
    }
    oauth.onFailure = { error in        // `error` is nil on cancel
        if nil != error {
            println("Authorization went wrong: \(error!.localizedDescription)")
        }
    }
  3. Now either use the built-in web view controller or manually open the authorize URL in the browser:

    Embedded (iOS):

    let vc = <# presenting view controller #>
    let web = oauth.authorizeEmbeddedFrom(vc, params: nil)
    oauth.afterAuthorizeOrFailure = { wasFailure, error in
        web.dismissViewControllerAnimated(true, completion: nil)
    }

    iOS browser:

    let url = oauth.authorizeURL()
    UIApplication.sharedApplication().openURL(url)

    Since you opened the authorize URL in the browser you will need to intercept the callback in your app delegate. Let the OAuth2 instance handle the full URL:

    func application(application: UIApplication!,
                     openURL url: NSURL!,
               sourceApplication: String!,
                      annotation: AnyObject!) -> Bool {
        // you should probably first check if this is your URL being opened
        if <# check #> { 
            oauth.handleRedirectURL(url)
        }
    }
  4. After everything completes either the onAuthorize or the onFailure closure will be called, and after that the afterAuthorizeOrFailure closure if it has been set.

  5. You can now obtain an OAuth2Request, which is an already signed NSMutableURLRequest, to retrieve data from your server.

    let req = oauth.request(forURL: <# resource URL #>)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(req) { data, response, error in
        if nil != error {
            // something went wrong
        }
        else {
            // check the response and the data
            // you have just received data with an OAuth2-signed request!
        }
    }
    task.resume()

Flows

Based on which OAuth2 flow that you need to use you will want to use the correct subclass. For a very nice explanation of OAuth's basics: The OAuth Bible.

Code Grant

For a full OAuth 2 code grant flow you want to use the OAuth2CodeGrant class. This flow is typically used by applications that can guard their secrets, like server-side apps, and not in distributed binaries. In case an application cannot guard its secret, such as a distributed iOS app, you would use the implicit grant or, in some cases, still a code grant but omitting the client secret.

Implicit Grant

An implicit grant is suitable for apps that are not capable of guarding their secret, such as distributed binaries or client-side web apps. Use the OAuth2ImplicitGrant class to receive a token and perform requests.

Would be nice to add another code example here, but it's pretty much the same as for the code grant.

Site-Specific Peculiarities

Some sites might not strictly adhere to the OAuth2 flow. The framework deals with those deviations by creating site-specific subclasses.

Playground

The idea is to add a Playground to see OAuth2 in use. However, it's not currently possible to interact view WebViews inside a playground, which would be needed to login to a demo server. Hence I made a sample OS X App that uses the GitHub API do demonstrate how you could use this framework.

There is some stub code in OSX.playground if you'd like to tinker. It's not working as one needs to open the authorize URL in a browser, then copy-paste the redirect URL from OS X's warning window into the Playground โ€“ which makes OAuth2 regenerate its state, making your redirect URL invalid. Fun times.

License

This code is released under the Apache 2.0 license, which means that you can use it in open as well as closed source projects. Since there is no NOTICE file there is nothing that you have to include in your product.

Copyright 2014 Pascal Pfiffner

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

oauth2's People

Contributors

p2 avatar tiagomnh avatar vojto avatar

Watchers

Arnaud Meunier 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.