Skip to content

codefiesta/OAuthKit

Repository files navigation

Build Xcode 16.4+ Swift 6.1+ iOS 18.0+ macOS 15.0+ tvOS 18.0+ visionOS 2.0+ watchOS 11.0+ License: MIT Code Coverage

OAuthKit

OAuthKit is a contemporary, event-driven Swift Package that utilizes the Observation Framework to implement the observer design pattern and publish OAuth 2.0 events. This enables application developers to effortlessly configure OAuth Providers and concentrate on developing exceptional applications rather than being preoccupied with the intricacies of authorization flows.

OAuthKit Features

OAuthKit is a small, lightweight package that provides out of the box Swift Concurrency safety support and Observable OAuth 2.0 state events that allow fine grained control over when and how to start authorization flows.

Key features include:

OAuthKit Installation

OAuthKit can be installed using Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/codefiesta/OAuthKit", from: "1.4.4")
]

OAuthKit Usage

The following is an example of the simplest usage of using OAuthKit across multiple platforms (iOS, macOS, visionOS, tvOS, watchOS):

import OAuthKit
import SwiftUI

@main
struct OAuthApp: App {

    @Environment(\.oauth)
    var oauth: OAuth
    
    /// Build the scene body
    var body: some Scene {

        WindowGroup {
            ContentView()
        }
        
        #if canImport(WebKit)
        WindowGroup(id: "oauth") {
            OAWebView(oauth: oauth)
        }
        #endif
    }
} 

struct ContentView: View {
    
    @Environment(\.oauth)
    var oauth: OAuth

    #if canImport(WebKit)
    @Environment(\.openWindow)
    var openWindow
    
    @Environment(\.dismissWindow)
    private var dismissWindow
    #endif

    /// The view body that reacts to oauth state changes
    var body: some View {
        VStack {
            switch oauth.state {
            case .empty:
                providerList
            case .authorizing(let provider, let grantType):
                Text("Authorizing [\(provider.id)] with [\(grantType.rawValue)]")
            case .requestingAccessToken(let provider):
                Text("Requesting Access Token [\(provider.id)]")
            case .requestingDeviceCode(let provider):
                Text("Requesting Device Code [\(provider.id)]")
            case .authorized(let provider, _):
                Button("Authorized [\(provider.id)]") {
                    oauth.clear()
                }
            case .receivedDeviceCode(_, let deviceCode):
                Text("To login, visit")
                Text(.init("[\(deviceCode.verificationUri)](\(deviceCode.verificationUri))"))
                    .foregroundStyle(.blue)
                Text("and enter the following code:")
                Text(deviceCode.userCode)
                    .padding()
                    .border(Color.primary)
                    .font(.title)
            }
        }
        .onChange(of: oauth.state) { _, state in
            handle(state: state)
        }
    }
    
    /// Displays a list of oauth providers.
    var providerList: some View {
        List(oauth.providers) { provider in
            Button(provider.id) {
                authorize(provider: provider)
            }
        }
    }

    /// Starts the authorization process for the specified provider.
    /// - Parameter provider: the provider to begin authorization for
    private func authorize(provider: OAuth.Provider) {
        #if canImport(WebKit)
        // Use the PKCE grantType for iOS, macOS, visionOS
        let grantType: OAuth.GrantType = .pkce(.init())
        #else
        // Use the Device Code grantType for tvOS, watchOS
        let grantType: OAuth.GrantType = .deviceCode
        #endif

        // Start the authorization flow
        oauth.authorize(provider: provider, grantType: grantType)
    }
    
    /// Reacts to oauth state changes by opening or closing authorization windows.
    /// - Parameter state: the published state change
    private func handle(state: OAuth.State) {
        #if canImport(WebKit)
        switch state {
        case .empty, .requestingAccessToken, .requestingDeviceCode:
            break
        case .authorizing, .receivedDeviceCode:
            openWindow(id: "oauth")
        case .authorized(_, _):
            dismissWindow(id: "oauth")
        }
        #endif
    }
}

OAuthKit Configuration

By default, the easiest way to configure OAuthKit is to simply drop an oauth.json file into your main bundle and it will get automatically loaded into your swift application and available as an Environment property wrapper. You can find an example oauth.json file here. OAuthKit provides flexible constructor options that allows developers to customize how their oauth client is initialized and what features they want to implement. See the oauth.init(_:bundle:options) method for details.

OAuth initialized from main bundle (default)

@Environment(\.oauth)
var oauth: OAuth

OAuth initialized from specified bundle

If you want to customize your OAuth environment or are using modules in your application, you can also specify which bundle to load configure files from:

let oauth: OAuth = .init(.module)

OAuth initialized with providers

If you are building your OAuth Providers programatically (recommended for production applications via a CI build pipeline for security purposes), you can pass providers and options as well.

let providers: [OAuth.Provider] = ...
let options: [OAuth.Option: Any] = [
    .applicationTag: "com.bundle.identifier",
    .autoRefresh: true,
    .useNonPersistentWebDataStore: true
]
let oauth: OAuth = .init(providers: providers, options: options)

OAuth initialized with custom URLSession

To support custom protocols or URL schemes that your app supports, developers can pass a custom .urlSession option that will allow the configuration of custom URLProtocol classes that can handle the loading of protocol-specific URL data.

// Custom URLSession
let configuration: URLSessionConfiguration = .ephemeral
configuration.protocolClasses = [CustomURLProtocol.self]
let urlSession: URLSession = .init(configuration: configuration)

let options: [OAuth.Option: Any] = [.urlSession: urlSession]
let oauth: OAuth = .init(.main, options: options)

OAuth initialized with Keychain protection and Private Browsing

OAuthKit allows you to protect access to your keychain items with biometrics until successful local authentication. If the .requireAuthenticationWithBiometricsOrCompanion option is set to true, the device owner will need to be authenticated by biometry or a companion device before keychain items (tokens) can be accessed. OAuthKit uses a default LAContext, but if you need fine-grained control while evaluating a user’s identity, pass your own custom LAContext to the options.

Developers can also implement private browsing by setting the .useNonPersistentWebDataStore option to true. This forces the WKWebView used during authorization flows to use a non-persistent data store, preventing data from being written to the file system.

// Custom LAContext
let localAuthentication: LAContext = .init()
localAuthentication.localizedReason = "read tokens from keychain"
localAuthentication.localizedFallbackTitle = "Use password"
localAuthentication.touchIDAuthenticationAllowableReuseDuration = 10

let options: [OAuth.Option: Any] = [
    .localAuthentication: localAuthentication,
    .requireAuthenticationWithBiometricsOrCompanion: true,
    .useNonPersistentWebDataStore: true,
]
let oauth: OAuth = .init(.main, options: options)

OAuthKit Authorization Flows

OAuth 2.0 authorization flows are started by calling the oauth.authorize(provider:grantType:) method.

A good resource to help understand the detailed steps involved in OAuth 2.0 authorization flows can be found on the OAuth 2.0 Playground.

oauth.authorize(provider: provider, grantType: grantType)

OAuth 2.0 Authorization Code Flow

The Authorization Code grant type is used by confidential and public clients to exchange an authorization code for an access token. It is recommended that all clients use the PKCE extension with this flow as well to provide better security.

// Generate a state and set the GrantType
let state: String = .secureRandom(32) // See String+Extensions
let grantType: OAuth.GrantType = .authorizationCode(state)
oauth.authorize(provider: provider, grantType: grantType)

OAuth 2.0 PKCE Flow

PKCE (RFC 7636) is an extension to the Authorization Code flow to prevent CSRF and authorization code injection attacks.

Proof Key for Code Exchange (PKCE) is the default and recommended flow to use in OAuthKit as this technique involves the client first creating a secret on each authorization request, and then using that secret again when exchanging the authorization code for an access token. This way if the code is intercepted, it will not be useful since the token request relies on the initial secret.

// PKCE is the default workflow with an auto generated pkce object
oauth.authorize(provider: provider)

// Or you can specify the workflow to use PKCE and inject your own values
let grantType: OAuth.GrantType = .pkce(.init())
oauth.authorize(provider: provider, grantType: grantType)

OAuth 2.0 Device Code Flow

OAuthKit supports the OAuth 2.0 Device Code Flow Grant, which is used by apps that don't have access to a web browser (like tvOS or watchOS). To leverage OAuthKit in tvOS or watchOS apps, simply add the deviceCodeURL to your OAuth.Provider.

let grantType: OAuth.GrantType = .deviceCode
oauth.authorize(provider: provider, grantType: grantType)

tvOS-screenshot

OAuth 2.0 Client Credentials Flow

The OAuth 2.0 Client Credentials flow is a mechanism where a client application authenticates itself to an authorization server using its own credentials rather than a user's credentials. This flow is primarily used in server-to-server communication, where a service or application needs to access a protected resource without involving a user.

let grantType: OAuth.GrantType = .clientCredentials
oauth.authorize(provider: provider, grantType: grantType)

OAuth 2.0 Provider Debugging

Debugging output with debugPrint(_:separator:terminator:) into the standard output is disabled by default. If you need to inspect response data received from providers, you can toggle the debug value to true. You can see an example here.

OAuthKit Sample Application

You can find a sample application integrated with OAuthKit here.

Security Best Practices

  1. Use the PKCE workflow if possible in your public applications.
  2. Never check in clientID or clientSecret values into source control. Although the clientID is public and the clientSecret is sensitive and private it is still widely regarded that both of these values should be always be treated as confidential.
  3. Don't include oauth.json files in your publicly distributed applications. It is possible for someone to inspect and reverse engineer the contents of your app and look at any files inside your app bundle which means you could potentially expose any confidential values contained in this file.
  4. Build OAuth Providers Programmatically via your CI Build Pipeline. Most continuous integration and delivery platforms have the ability to generate source code during build workflows that can get compiled into Swift byte code. It's should be feasible to write a step in the CI pipeline that generates a .swift file that provides access to a list of OAuth.Provider objects that have their confidential values set from the secure CI platform secret keys. This swift code can then compiled into the application as byte code. In practical terms, the security and obfuscation inherent in compiled languages make extracting confidential values difficult (but not impossible).
  5. OAuth 2.0 providers shouldn't provide the ability for publicly distributed applications to initiate Client Credentials workflows since it is possible for someone to extract your secrets.

OAuth 2.0 Providers

OAuthKit should work with any standard OAuth2 provider. Below is a list of tested providers along with their OAuth2 documentation links. If you’re interested in seeing support or examples for a provider not listed here, please open an issue on our here.

  • Auth0 / Okta
  • Box
  • Dropbox
  • Github
  • Google
    • Important: When creating a Google OAuth2 application from the Google API Console create an OAuth 2.0 Client type of Web Application (not iOS).
  • LinkedIn
    • Important: When creating a LinkedIn OAuth2 provider, you will need to explicitly set the encodeHttpBody property to false otherwise the /token request will fail. Unfortunately, OAuth providers vary in the way they decode the parameters of that request (either encoded into the httpBody or as query parameters). See sample oauth.json.
    • LinkedIn currently doesn't support PKCE.
  • Instagram
  • Microsoft
    • Important: When registering an application inside the Microsoft Azure Portal it's important to choose a Redirect URI as Web otherwise the /token endpoint will return an error when sending the client_secret in the body payload.
  • Slack
    • Important: Slack will block unknown browsers from initiating OAuth workflows. See sample oauth.json for setting the customUserAgent as a workaround.
  • Stripe
  • Twitter
    • Unsupported: Although OAuthKit should work with Twitter/X OAuth2 APIs without any modification, @codefiesta has chosen not to support any Elon Musk backed ventures due to his facist, racist, and divisive behavior that epitomizes out-of-touch wealth and greed. @codefiesta will not raise objections to other developers who wish to contribute to OAuthKit in order to support Twitter OAuth2.

OAuthKit Documentation

You can find the complete Swift DocC documentation for the OAuthKit Framework here.