• Stars
    star
    636
  • Rank 67,979 (Top 2 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Note

Sadly, this repository is no longer able to be actively maintained. If you would like to take over the repo please feel free to get in touch.

Heimdallr

Heimdallr 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 an Android Developer, please take a look at the Android version of Heimdallr.

Build Status Carthage compatible Cocoapods platforms GitHub release (latest by date)

Example

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

let tokenURL = URL(string: "https://example.com/oauth/v2/token")!
let heimdallr = Heimdallr(tokenURL: tokenURL)

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

heimdallr.requestAccessToken(username: "johndoe", password: "A3ddj3w") { result in
    switch result {
    case .success:
        print("success")
    case .failure(let error):
        print("failure: \(error.localizedDescription)")
    }
}

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

var session: URLSession!
var request: URLRequest!

heimdallr.authenticateRequest(request) { result in
    switch result {
    case .success(let request):
        let task = session.dataTask(with: request) { data, response, error in
            // ...
        }
        
        task.resume()
    case .failure(let error):
        print("failure: \(error.localizedDescription)")
    }
}

Installation

Installation is possible via Swift Package Manager, Carthage, or CocoaPods, see below for either method:

Swift Package Manager

In Xcode:

  1. Navigate to File -> Swift Packages -> Add Package Dependency to add the Swift package.

  2. Paste the repository URL into the search box https://github.com/trivago/Heimdallr.swift.git.

  3. Select the version, branch, or commit to install.

  4. Select the product and the target to attach it to.

Carthage

Carthage is a simple, decentralized dependency manager for Cocoa.

  1. Add Heimdallr to your Cartfile:

    github "trivago/Heimdallr.swift" ~> 3.6.1
    
  2. Run carthage update to fetch and build Heimdallr and its dependencies.

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

CocoaPods

  1. Add Heimdallr to your Podfile:

    pod 'Heimdallr', '~> 3.6.1'
  2. Run pod install to fetch and build Heimdallr and its dependencies.

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?
}

Heimdallr ships with an already built-in persistent keychain-based access token store. The service is configurable:

var service: String!

let accessTokenStore = OAuthAccessTokenKeychainStore(service: service)

HeimdallrHTTPClient

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

protocol HeimdallrHTTPClient {
    func sendRequest(request: URLRequest, completion: (data: Data!, response: URLResponse!, error: Error?) -> ())
}

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

var urlSession: URLSession!

let httpClient = HeimdallrHTTPClientURLSession(urlSession: session)

OAuthAccessTokenParser

You can provide your own parser to handle the access token response of the server. It can be useful for parsing additional parameters sent in the response that your application may need. The parser must implement the following parse method:

protocol OAuthAccessTokenParser {
    func parse(data: Data) -> Result<OAuthAccessToken, Error>
}

Heimdallr

Heimdallr 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: URL!

let heimdallr = Heimdallr(tokenURL: tokenURL)
             // Heimdallr(tokenURL: tokenURL, credentials: credentials)
             // Heimdallr(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore)
             // Heimdallr(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore, accessTokenParser: accessTokenParser)
             // Heimdallr(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore, accessTokenParser: accessTokenParser, httpClient: httpClient)
             // Heimdallr(tokenURL: tokenURL, credentials: credentials, accessTokenStore: accessTokenStore, accessTokenParser: accessTokenParser, 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!

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

The completion closure may be invoked on any thread.

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

var request: URLRequest!

heimdallr.authenticateRequest(request) { result in
    // ...
}

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

HeimdallrResourceRequestAuthenticator

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

About

Heimdallr was built by trivago 🏭

Credits

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

More Repositories

1

prettier-plugin-sort-imports

A prettier plugin to sort imports in typescript and javascript files by the provided RegEx order.
TypeScript
2,939
star
2

parallel-webpack

Builds multi-config webpack projects in parallel
JavaScript
1,484
star
3

gollum

An n:m message multiplexer written in Go
Go
935
star
4

Heimdall.droid

Easy to use OAuth 2 library for Android by trivago.
Kotlin
257
star
5

cluecumber

Clear and concise reporting for the Cucumber BDD JSON format.
Java
254
star
6

melody

Melody is a library for building JavaScript web applications.
JavaScript
215
star
7

Dobby

Swift helpers for mocking and stubbing
Swift
165
star
8

prettier-plugin-twig-melody

Code formatting plugin for Prettier which can handle Twig/Melody templates
JavaScript
153
star
9

cucable-plugin

Maven plugin that simplifies running Cucumber Scenarios in parallel.
Java
112
star
10

triava

The triava project contains several of trivago's core libraries for Java-based projects: caching, collections, annotations, concurrency libraries and more.
Java
74
star
11

scalad

Horizontal Job Autoscaler for Nomad
Go
69
star
12

tgo

trivago go utilities
Go
57
star
13

hamara

Export datasource from the existing Grafana DB into a YAML provisioning file
Go
56
star
14

jade

A simple but yet powerful library to expose your entities through JSON API.
PHP
55
star
15

nomad-pot-driver

Nomad task driver for launching freebsd jails.
Go
54
star
16

Protector

A circuit breaker for InfluxDB
Python
48
star
17

fastutil-concurrent-wrapper

Set of concurrent wrappers around fastutil primitive maps
Java
32
star
18

babel-plugin-cloudinary

Compile cloudinary URLs at build time.
JavaScript
24
star
19

pbf-loader

Webpack loader for .proto files to be used within mapbox/pbf
JavaScript
21
star
20

rumi

trivago continuous integration executor
PHP
20
star
21

influxdbviewer

JavaScript
18
star
22

samsa

A high level NodeJS stream processing library
TypeScript
18
star
23

preact-hooks-testing-library

preact port of https://github.com/testing-library/react-hooks-testing-library
TypeScript
18
star
24

project-ironman

CSS skeleton / structure we used at trivago for our large scale refactoring project called Project Ironman
CSS
17
star
25

logstash-codec-protobuf

Protobuf codec for parsing data into logstash
17
star
26

jcha

Java Class Histogram Analyser
Java
17
star
27

reportoire

Kotlin
15
star
28

ReactiveHeimdall

Reactive wrapper around Heimdall.swift
Swift
14
star
29

chapi

chronos & marathon console client - Manage your jobs like a git repository
PHP
14
star
30

hive-lambda-sting

A small library of hive UDFS using Macros to process and manipulate complex types
Java
14
star
31

rebase

A small python library to make your data layer more robust.
Python
13
star
32

Mail-Pigeon

Mail Pigeon is a mail delivery plattform, which was created in the trivago developer days (something like the Google 20% rule) to replace some of the PHP based mailing scripts that were present that days. trivago has a lot of customers and therefore the focus laid on the fast and relyable sending process of a future mail tool. We decided to build a plattform that just can send mails in a performant manner, later on we built mail pigeon on top of it.
Java
13
star
33

boerewors

Release framework based on Python
Python
11
star
34

rtl-scss-kit

A right-to-left mixin set to create right-to-left and left-to-right css out of one scss-source
CSS
8
star
35

svn-daemon

A daemon to control a svn checkout via a web interface, written in go.
Go
8
star
36

triversity

trivago's university collaboration tool
Vue
7
star
37

exporter-edgecast

A Prometheus exporter for the Edgecast CDN
Go
7
star
38

junior-java-software-engineer-casestudy

Case study for Junior Software Engineer - Java Backend Services
7
star
39

libvips-mozjpeg-amazonlinux-buildscript

Modified libvips build script which helps to build libvips with mozjpeg support on AWS 'AmazonLinux' EC2 instances.
Shell
7
star
40

exporter-chinacache

A Prometheus exporter for the Chinacache CDN
Go
5
star
41

express-booking-selfconnect-api

trivago Express Booking - Self Connect API
PHP
5
star
42

recsys-challenge-2019-benchmarks

Run benchmark algorithms on the data sets of the RecSys Challenge 2019. https://recsys.trivago.cloud/
Python
4
star
43

create-melody-app

Create Melody apps quickly from the command line.
JavaScript
3
star
44

oauth-sdk-js

A tiny javascript library that allows to log in/register with trivago
JavaScript
2
star
45

melody-web

Public web site of the Melody JavaScript framework
HTML
2
star
46

.github

@trivago organization
2
star
47

intellij-idea-plugin

Internal IntelliJ plugin by trivago. Quick and dirty implementation.
Kotlin
1
star
48

melody-template

Melody Starter Example
JavaScript
1
star
49

mod_whatkilledus

Copy of sources from https://emptyhammock.com/projects/httpd/diag/
C
1
star
50

TriMamba

Collection of tools aimed to gather event information from different sources into a database
JavaScript
1
star
51

trivago-gtm-template

GTM template implementation for the trivago Conversion API
Smarty
1
star