GithubHelp home page GithubHelp logo

callam / heimdall.swift Goto Github PK

View Code? Open in Web Editor NEW

This project forked from trivago/heimdallr.swift

0.0 2.0 0.0 1.95 MB

Easy to use OAuth 2 library for iOS, written in Swift by Rheinfabrik.

Home Page: http://rheinfabrik.github.io/Heimdall.swift/

License: Apache License 2.0

Objective-C 0.27% Swift 97.62% Makefile 0.10% Shell 2.00%

heimdall.swift's Introduction

Heimdall

Heimdall is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant flow, refreshing an access token as well as extension grants.

If you are familiar with ReactiveCocoa, also check out ReactiveHeimdall!

If you are an Android Developer then please take a look at the Android version of Heimdall.

Build Status

Example

Before requesting an access token, the client must be configured appropriately:

let tokenURL = NSURL(string: "http://example.com/oauth/v2/token")!
let heimdall = Heimdall(tokenURL: tokenURL)

On login, the resource owner's password credentials are used to request an access token:

heimdall.requestAccessToken(username: "johndoe", password: "A3ddj3w") { result in
    switch result {
    case .Success:
        println("success")
    case .Failure(let error):
        println("failure: \(error.unbox.localizedDescription)")
    }
}

Heimdall automatically persists the access token. Afterwards, any NSURLRequest can be easily authenticated using the received access token:

var session: NSURLSession!
var request: NSURLRequest!

heimdall.authenticateRequest(request) { result
    switch result {
    case .Success(let request):
        let task = session.dataTaskWithRequest(request.unbox) { data, response, error in
            // ...
        }

        task.resume()
    case .Failure(let error):
        println("failure: \(error.unbox.localizedDescription)")
    }
}

Installation

Carthage

Carthage is a simple, decentralized dependency manager for Cocoa.

  1. Add Heimdall to your Cartfile:
github "rheinfabrik/Heimdall.swift" ~> 1.1
  1. Run carthage update to fetch and build Heimdall and its dependencies.

  2. Make sure your application's target links against Heimdall.framework and copies all relevant frameworks into its application bundle (iOS); or embeds the binaries of all relevant frameworks (Mac).

Usage

OAuthClientCredentials

The client credentials, consisting of the client's identifier and optionally its secret, are used for authenticating with the token endpoint:

var identifier: String!
var secret: String!

let credentials = OAuthClientCredentials(id: identifier)
               // OAuthClientCredentials(id: identifier, secret: secret)

Please note that native applications are considered to be public clients.

OAuthAccessTokenStore

An access token store is used to (persistently) store an access token received from the token endpoint. It must implement the following storage and retrieval methods:

protocol OAuthAccessTokenStore {
    func storeAccessToken(accessToken: OAuthAccessToken?)
    func retrieveAccessToken() -> OAuthAccessToken?
}

Heimdall ships with an already built-in persistent Keychain-based access token store, using KeychainAccess. The service is configurable:

var service: String!

let accessTokenStore = OAuthAccessTokenKeychainStore(service: service)

HeimdallHTTPClient

An HTTP client that can be used by Heimdall for requesting access tokens. It must implement the following sendRequest method:

protocol HeimdallHTTPClient {
    func sendRequest(request: NSURLRequest, completion: (data: NSData!, response: NSURLResponse!, error: NSError?) -> ())
}

For convenience, a default HTTP client named HeimdallHTTPClientNSURLSession and based on NSURLSession is provided. It may be configured with an NSURLSession:

var urlSession: NSURLSession!

let httpClient = HeimdallHTTPClientNSURLSession(urlSession: session)

Heimdall

Heimdall must be initialized with the token endpoint URL and can optionally be configured with client credentials, an access token store and an HTTP client:

var tokenURL: NSURL!

let heimdall = Heimdall(tokenURL: tokenURL)
            // Heimdall(tokenURL: tokenURL, credentials: credentials)
            // Heimdall(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore)
            // Heimdall(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore, httpClient: httpClient)
            // Heimdall(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore, httpClient: httpClient, resourceRequestAuthenticator: resourceRequestAuthenticator)

Whether the client's access token store currently holds an access token can be checked using the hasAccessToken property. It's not checked whether the stored access token, if any, has already expired.

The authorize method takes the resource owner's password credentials as parameters and uses them to request an access token from the token endpoint:

var username: String!
var password: String!

heimdall.requestAccessToken(username: username, password: password) { result in
    // ...
}

The completion closure may be invoked on any thread.

Once successfully authorized, any NSURLRequest can be easily altered to include authentication via the received access token:

var request: NSURLRequest!

heimdall.authenticateRequest(request) { result
    // ...
}

If the access token has already expired and a refresh token is available, Heimdall will automatically refresh the access token. Refreshing requires network I/O. The completion closure may be invoked on any thread.

HeimdallResourceRequestAuthenticator

By default, Heimdall authenticates a request by setting the HTTP header field Authorization. This behavior can be changed by passing another resource request authenticator implementing HeimdallResourceRequestAuthenticator to the initializer.

About

Heimdall was built by Rheinfabrik ๐Ÿญ

Credits

Contains code for query string escaping taken from Alamofire (MIT License)

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.