Swift async/await OAuth 2.0 HTTP request library.

Overview

SwAuth

Codacy Badge SPM Swift Platforms

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

  • Usable and beautiful syntax with async/await! Kiss completion handler hell and the closure jungle goodbye!
  • Supports Authorization Code Grant (RFC 6749/6750), Proof Key for Code Exchange (PKCE) extension for Authorization Code Grant (RFC 7636), and the Device Authorization Grant (RFC 8628).
  • Support for all Apple device platforms.
  • Retry errored requests.
  • Automatically refreshes tokens.
  • Tokens stored on Keychain and cross-site request forgery mitigation by default.
  • Easily deal with JSON responses with SwiftyJSON built-in.
  • Easily integrate with SwiftUI.
  • Complete, meticulous, thorough, documentation.
  • Errors that are probably, maybe actually useful.
  • Built on SwiftNIO with AsyncHTTPClient.
  • QR Code for the Device Authorization Flow (tvOS/watchOS).
  • Sample/Example Apps.

Requirements

  • Xcode 13+
  • iOS 15.0+ | macOS 12.0+ | watchOS 8.0+ | tvOS 15.0+

Installation/Integration

Use the Swift Package Manager to add SwAuth to your project! Simply add the package to dependencies in your Package.swift:

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/Colaski/SwAuth.git", from: "1.0.0"),
    ]
)

Basic Usage

  1. Import SwAuth in files you wish to use it's amazing features:
import SwAuth
  1. Create an instance of keychain:
let keychain = Keychain(service: "com.your.bundleID",
                        accessGroup: "appIdentifierPrefix.com.your.bundleID").label("Your App Name")
  1. Create an instance of the proper authorization flow for your Web API.
let keychain = Keychain(service: "com.your.bundleID",
                        accessGroup: "appIdentifierPrefix.com.your.bundleID").label("Your App Name")

let spotify = PKCEAuthorizationFlow(clientID: "YourClientID",
                                    authorizationEndpoint: URL(string: "https://accounts.spotify.com/authorize")!,
                                    tokenEndpoint: URL(string: "https://accounts.spotify.com/api/token")!,
                                    redirectURI: "someapp://callback",
                                    keychain: keychain,
                                    scopes: "user-follow-modify")
  1. Start an ASWebAuthenticationSession like in the example app with the instance's authorization URL:
spotify.authorizationURL
  1. Pass the callback URL from the ASWebAuthenticationSession into the provided handler method:
do {
    try await spotify.authorizationResponseHandler(for: callbackURL)
} catch {
    print(error.localizedDescription)
}
  1. Make an authorized request:
do {
    // https://developer.spotify.com/documentation/web-api/reference/#/operations/follow-artists-users
    var request = HTTPRequest(endpoint: URL(sting: "https://api.spotify.com/v1/me/following")!)
    request.httpMethod = .PUT
    request.endpointQueryItems = ["type": "artist"]
    request.httpBody = ["ids": ["5K4W6rqBFWDnAN6FQUkS6x"]]
    request.bodyEncoding = .JSON

    // Send an authenticated HTTP request, this one will follow the artist Kanye on Spotify.
    let json = try await spotify.authenticatedRequest(for: request, numberOfRetries: 2).json()
    
    // Prints the JSON output
    print(json)
} catch {
    print(error.localizedDescription)
}

For more information, read my beautiful documentation: https://swauth.netlify.app/documentation/Swauth

Contributing

Contributions are welcome!

Make sure swift is installed and then

git clone https://github.com/Colaski/SwAuth.git
cd SwAuth
swift build

Make your changes and submit and a PR for review!

Nice to have list:

  • Include ready to go implementations of Web API's with endpoints like in the example app

    • Perhaps Spotify, Google, Azure/Microsoft, Github etc.
  • OAuth 1.0 support

You might also like...
A swift implementation of OAuth2

#AlamofireOauth2 A Swift implementation of OAuth2 for iOS using Alamofire. #Intro This library is heavilly inspired by the SwiftOAuth2 repository from

Declarative Swift framework for Attributed Role-based Access Control management
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:

SFA: Swift Firebase Auth Project✨
SFA: Swift Firebase Auth Project✨

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

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

Minimalist HTTP request library via async / await

Making HTTP API requests in Swift using Foundation can be verbose and use a mix of types like URL, URLComponents and URLRequest to form a request and then handling all the encoding and decoding steps later

🤵🏽‍♀️ Janet — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveraging the power of async/await.

🤵🏽‍♀️ Janet — Just another networking kit — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveragi

Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift
Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

⚡️ Lightweight full-featured Promises, Async & Await Library in Swift
⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

AsyncHTTP - Generic networking library written using Swift async/await

Generic networking library written using Swift async/await

Hydra: Lightweight full-featured Promises, Async-Await Library in Swift

Async Functions for ECMAScript The introduction of Promises and Generators in EC

An Generic HTTP Request Library For Swift

GRequest An HTTP request library written in Swift. ##Basic Usage Be simple, as it should be: Request("https://api.github.com/repos/lingoer/SwiftyJSON/

Lightweight async/await networking library with interceptor support - usable from iOS 13+.
Lightweight async/await networking library with interceptor support - usable from iOS 13+.

Lightweight async/await networking library with interceptor support. 🚀 Getting started AsyncNetwork's session acts as a wrapper to URLSession by addi

Swift TableView pagination with async API request.
Swift TableView pagination with async API request.

SwiftTableViewPagination Swift TableView pagination with async API request. Output UML Create puml file. $ cd SwiftTableViewPagination/scripts/swiftum

Fetch Multiple Rest API using Swift 5.5 Async Await with Task, TaskGroup, Continuation API
Fetch Multiple Rest API using Swift 5.5 Async Await with Task, TaskGroup, Continuation API

Source code for Tutorial on experimenting with Swift Async Await to fetch multiple REST API endpoints and eliminate Pyramid of Doom callback hell to improve code readability and maintanability

⏳ Collection of Swift 5.5 async/await utility functions.

⏳ FunAsync Collection of Swift 5.5 async/await utility functions. Throw - Result conversion asyncThrowsToAsyncResult asyncResultToAsyncThrows More C

🎭 Swift async/await & Actor-powered effectful state-management framework.
🎭 Swift async/await & Actor-powered effectful state-management framework.

🎭 Actomaton 🧑‍🎤 Actor + 🤖 Automaton = 🎭 Actomaton Actomaton is Swift async/await & Actor-powered effectful state-management framework inspired by

A lightweight swift network layer with Combine, Async-Await, and a traditional completion block.

CombineNetwork A simple light-weight network library to make network requesting simpler. It supports newer techonology such as async/await as well as

AnimeListSwiftUI - Anime quote list built with MVVM Swift 5 using Async/Await

How To In SwiftUI Async/Await AnimeListSwiftUI - Anime quote list built with MVVM Swift 5 using Async/Await Clones Clubhouse - App clone built with Sw

async and await for Swift.
async and await for Swift.

async and await for Swift. Usage Beta version. New docs soon... Contribute If you have any problems or need more information, please open an issue usi

Comments
  • Get unexpired access token

    Get unexpired access token

    Is your feature request related to a problem? Please describe.

    • I See that the framework can create the access token automatically with the refresh token, if you do a request.

    Describe the solution you'd like

    • Is there a way to get the access token string - that is not expired - manually?
    question 
    opened by dungi 8
Releases(1.1.0)
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
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

OAuthSwift 3.1k Jan 3, 2023
A simple OAuth library for iOS with a built-in set of providers

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:

Damien 477 Oct 15, 2022
A simple to use, standard interface for authenticating to oauth 2.0 protected endpoints via SFSafariViewController.

AuthenticationViewController A simple to use, standard interface for authenticating to OAuth 2.0 protected endpoints via SFSafariViewController. Instr

Raul Riera 256 Dec 14, 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
A simple library to make authenticating tvOS apps easy via their iOS counterparts.

Voucher The new Apple TV is amazing but the keyboard input leaves a lot to be desired. Instead of making your users type credentials into their TV, yo

Riz 516 Nov 24, 2022
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
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

Pascal Pfiffner 1.1k Jan 2, 2023