A swift implementation of OAuth2

Overview

#AlamofireOauth2

A Swift implementation of OAuth2 for iOS using Alamofire.

Build Status Issues Stars Version License Platform

Git Twitter LinkedIn Website eMail

#Intro

This library is heavilly inspired by the SwiftOAuth2 repository from crousselle

AlamofireOauth2 relies on Alamofire, and KeychainAccess

Using AlamofireOauth2 in your own App

'AlamofireOauth2' is now available through the dependency manager CocoaPods. You do have to use cocoapods version 0.36. At this moment this can be installed by executing:

[sudo] gem install cocoapods

If you have installed cocoapods version 0.36 or later, then you can just add EVCloudKitDao to your workspace by adding the folowing 2 lines to your Podfile:

use_frameworks!
pod "AlamofireOauth2"

I have now moved on to Swift 2. If you want to use AlamofireOauth2, then get that version by using the podfile command:

use_frameworks!
pod "AlamofireOauth2", '~> 1.0'

Version 0.36 of cocoapods will make a dynamic framework of all the pods that you use. Because of that it's only supported in iOS 8.0 or later. When using a framework, you also have to add an import at the top of your swift file like this:

import AlamofireOauth2

If you want support for older versions than iOS 8.0, then you can also just copy the AlamofireOauth2 folder containing the 4 classes to your app. besides that you also have to embed the Alamofire, and KeychainAccess libraries

Building the AlamofireOaut2Test demo

  1. Clone the repo to a working directory

  2. CocoaPods is used to manage dependencies. Pods are setup easily and are distributed via a ruby gem. Follow the simple instructions on the website to setup. After setup, run the following command from the toplevel directory of AlamofireOauth to download the dependencies for AlamofireOauth:

pod install
  1. Open the AlamofireOauth.xcworkspace in Xcode and.

  2. Create your own clientID and clientSecret at https://developer.wordpress.com/docs/oauth2/

  3. set the clientID and clientSecret in the wordpressOauth2Settings object in the ViewController

and you are ready to go!

How to use the AlamofireOauth

Below is the sample code for a simple call to the WordPress API while authenticating using OAuth2

class ViewController: UIViewController {

    @IBOutlet weak var result: UITextView!

    @IBAction func startWordpressOauth2Test(sender: AnyObject) {
        self.result.text = ""
        UsingOauth2(wordpressOauth2Settings, self, { token in
            WordPressRequestConvertible.OAuthToken = token
            Alamofire.request(WordPressRequestConvertible.Me())
                .responseJSON { (request, response, json, error ) -> Void in
                self.result.text = "\(json)"
                println("JSON = \(json)")
            }
        }, {
            println("Oauth2 failed")
        })
    }
}

// Create your own clientID and clientSecret at https://developer.wordpress.com/docs/oauth2/
let wordpressOauth2Settings = Oauth2Settings(
    baseURL: "https://public-api.wordpress.com/rest/v1",
    authorizeURL: "https://public-api.wordpress.com/oauth2/authorize",
    tokenURL: "https://public-api.wordpress.com/oauth2/token",
    redirectURL: "alamofireoauth2://wordpress/oauth_callback",
    clientID: "????????????",
    clientSecret: "????????????"
)

// Minimal Alamofire implementation. For more info see https://github.com/Alamofire/Alamofire#crud--authorization
public enum WordPressRequestConvertible: URLRequestConvertible {
    static var baseURLString: String? = wordpressOauth2Settings.baseURL
    static var OAuthToken: String?

    case Me()

    public var URLRequest: NSURLRequest {
        let URL = NSURL(string: WordPressRequestConvertible.baseURLString!)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent("/me"))
        mutableURLRequest.HTTPMethod = "GET"

        if let token = WordPressRequestConvertible.OAuthToken {
            mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        }

        return mutableURLRequest
    }
}

License

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

My other libraries:

Also see my other open source iOS libraries:

  • EVReflection - Reflection based (Dictionary, CKRecord, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift
  • EVCloudKitDao - Simplified access to Apple's CloudKit
  • EVFaceTracker - Calculate the distance and angle of your device with regards to your face in order to simulate a 3D effect
  • EVURLCache - a NSURLCache subclass for handling all web requests that use NSURLReques
  • AlamofireOauth2 - A swift implementation of OAuth2 using Alamofire
  • EVWordPressAPI - Swift Implementation of the WordPress (Jetpack) API using AlamofireOauth2, AlomofireJsonToObjects and EVReflection (work in progress)
  • PassportScanner - Scan the MRZ code of a passport and extract the firstname, lastname, passport number, nationality, date of birth, expiration date and personal numer.
  • AttributedTextView - Easiest way to create an attributed UITextView with support for multiple links (url, hashtags, mentions).
You might also like...
Swift based OAuth library for iOS and macOS
Swift based OAuth library for iOS and macOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuth2 framework for macOS and iOS, written in Swift.
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation 🛠 Usage 🖥 Sample macOS app (with data loader examples) 📖 Tec

OAuth2 framework for macOS and iOS, written in Swift.
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation 🛠 Usage 🖥 Sample macOS app (with data loader examples) 📖 Tec

A swift SDK for Medium's OAuth2 API

Medium SDK - Swift A library to allow access to Medium API for any Swift iOS application. Features Medium.com authorization & token handling Login sta

Simple OAuth2 library with a support of multiple services.

Simple OAuth2 library with a support of multiple services.

Example of simple OAuth2 authentication using Alamofire 5 and RxSwift library

REST Client based on Alamofire 5 and RxSwift library. Supports OAuth2 and Basic authentication interceptor.

Linenoise-Swift  A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement.
Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement.

Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement. Supports Mac OS and Linux Line edit

Simplex-Swift - A basic implementation of the Simplex algorithm, written in Swift

Simplex-Swift - A basic implementation of the Simplex algorithm, written in Swift

Fancy Swift implementation of the Visual Format Language (experimental and doesn't work with the recent version of Swift)
Fancy Swift implementation of the Visual Format Language (experimental and doesn't work with the recent version of Swift)

VFLToolbox Autolayout is awesome! VFL a.k.a Visual Format Language is even more awesome because it allows you to shorten constraints setting code. The

Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway
Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway

Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway deployed on Graviton arm64 build swift:5.6.2-amazonlinux2-docker image

Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)
Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)

With the introduction of Combine and SwiftUI, we will face some transition periods in our code base. Our applications will use both Combine and a thir

Swift implementation of the longest common subsequence (LCS) algorithm.

SwiftLCS SwitLCS provides an extension of Collection that finds the indexes of the longest common subsequence with another collection. The longest com

Swift implementation of Github REST API v3
Swift implementation of Github REST API v3

GitHubAPI Swift implementation of GitHub REST api v3. Library support Swift 4.2. Work is in progress. Currently supported: Issues API. Activity API(Fe

A simple and beautiful chart lib used in Piner and CoinsMan for iOS(https://github.com/kevinzhow/PNChart) Swift Implementation

PNChart-Swift PNChart(https://github.com/kevinzhow/PNChart) Swift Implementation Installation This isn't on CocoaPods yet, so to install, add this to

ReSwift is a Redux-like implementation of the unidirectional data flow architecture in Swift.
ReSwift is a Redux-like implementation of the unidirectional data flow architecture in Swift.

ReSwift is a Redux-like implementation of the unidirectional data flow architecture in Swift. ReSwift helps you to separate three important concerns of your app's components.

When is a lightweight implementation of Promises in Swift
When is a lightweight implementation of Promises in Swift

Description When is a lightweight implementation of Promises in Swift. It doesn't include any helper functions for iOS and OSX and it's intentional, t

A Swift implementation of fastimage. Supports PNG, GIF, and JPEG.
A Swift implementation of fastimage. Supports PNG, GIF, and JPEG.

ImageScout ImageScout is a Swift implementation of fastimage. It allows you to find the size and type of a remote image by downloading as little as po

FlexLayout adds a nice Swift interface to the highly optimized facebook/yoga flexbox implementation. Concise, intuitive & chainable syntax.
FlexLayout adds a nice Swift interface to the highly optimized facebook/yoga flexbox implementation. Concise, intuitive & chainable syntax.

FlexLayout adds a nice Swift interface to the highly optimized Yoga flexbox implementation. Concise, intuitive & chainable syntax. Flexbox is an incre

Implementation of x-callback-url (Inter app communication) in swift
Implementation of x-callback-url (Inter app communication) in swift

CallbackURLKit - Inter app communication Starting to integrate URL scheme in an app, why not be compliant with x-callback-url. CallbackURLKit.register

Comments
  • Explicitly request application/json when fetching a token; fixes GitH…

    Explicitly request application/json when fetching a token; fixes GitH…

    opened by jrmiddle 1
  • Fix to manage a nil access token callback error.

    Fix to manage a nil access token callback error.

    This for example happens when in the Linkedin login form the user insert a mail and add a space at the end. The oauth fails, the token is null, but the OAuth2Client class don't call the error clousure, so the error couldn't be managed from the app usign this lib.

    opened by MartinaMuscarella 1
  • request authorize error

    request authorize error

    i have found some problem with string url encoding

            let url:String! = self.oauth2Settings.authorizeURL + "?response_type=code&client_id=" + self.oauth2Settings.clientID + "&redirect_uri=" + self.oauth2Settings.redirectURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlHostAllowed)! + "&scope=" + self.oauth2Settings.scope + "&state=" + expectedState
            
            let urlRequest : NSURLRequest = NSURLRequest(url: NSURL(string: url)! as URL)
            
            self.webView!.loadRequest(urlRequest as URLRequest)
    

    converting string to NSURL will raise nil error, i have solution to add

     `   let urlRequest : NSURLRequest = NSURLRequest(url: NSURL(string: url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)! as URL)`
    

    thank you very much

    opened by masfu 1
Releases(2.0.3)
Owner
Edwin Vermeer
Edwin Vermeer
Simple OAuth2 library with a support of multiple services.

Simple OAuth2 library with a support of multiple services.

HyperRedink 68 May 13, 2022
Example of simple OAuth2 authentication using Alamofire 5 and RxSwift library

REST Client based on Alamofire 5 and RxSwift library. Supports OAuth2 and Basic authentication interceptor.

Tomáš Smolík 3 Dec 8, 2022
SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API.

SpotifyLogin SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API. Usage of this framework is bound under the Developer Terms o

Spotify 343 Dec 8, 2022
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
Swift based OAuth library for iOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuthSwift 3.1k Jan 3, 2023
Declarative Swift framework for Attributed Role-based Access Control management

Koosa Declarative Swift framework for Attributed Role-based Access Control management Check out this blog post for full explanation and more details:

Mostafa Abdellateef 37 Oct 24, 2022
FCLAuthSwift is a Swift library for the Flow Client Library (FCL) that enables Flow wallet authentication on iOS devices.

FCLAuthSwift is a Swift library for the Flow Client Library (FCL) that enables Flow wallet authentication on iOS devices. Demo The demo a

Zed 3 May 2, 2022
SFA: Swift Firebase Auth Project✨

SFAssets SFA: Swift Firebase Auth Project✨ 파이어베이스로 로그인/회원가입 뿌수기 Login View (로그인 뷰) 담당 기능 배정 Facebook Login 후릐 Google Login 태끼 Apple Login 이준초이 Github

null 6 Nov 7, 2021
An poc to make a login using Auth0 in Swift

Swift-Auth0-poc This app is an poc to make a login using Auth0. If you want to try it yourself here is a small tutorial on how to do it. 1. Configure

Sem de Wilde 1 Jan 21, 2022
Swift async/await OAuth 2.0 HTTP request library.

SwAuth SwAuth is an OAuth 2.0 HTTP request library written in Swift iOS 15.0+, macOS 12.0+, watchOS 8.0+, and tvOS 15.0+. Features Requirements Instal

Colaski 17 Nov 5, 2022