codefiesta/OAuthKit
A modern and observable framework for OAuth 2.0 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:
- Simple Configuration
- Keychain protection with biometrics or companion device
- Private Browsing with non-persistent WebKit Datastores
- Custom URLSession configuration for complete control custom protocol specific data
- Observable State driven events to allow full control over when and if users are prompted to authenticate with an OAuth provider
- Supports all Apple Platforms (iOS, macOS, tvOS, visionOS, watchOS)
- Support for every OAuth 2.0 Flow
- Authorization Code - PKCE - Device Code - Client Credentials - OpenID Connect
OAuthKit Installation
OAuthKit can be installed using Swift Package Manager.
dependencies: [
.package(url: "https://github.com/codefiesta/OAuthKit", from: "2.1.0")
]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)
case .error(let provider, let error):
Text("Error [\(provider.id)]: \(error.localizedDescription)")
}
}
.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, .error, .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: OAuthOAuth 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)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
- Use the PKCE workflow if possible in your public applications.
- 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.
- Don't include
oauth.jsonfiles 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. - 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).
- 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.
* Important: When creating a Google OAuth2 application from the Google API Console create an OAuth 2.0 Client type of Web Application (not iOS).
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.
* 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.
* Important: Slack will block unknown browsers from initiating OAuth workflows. See sample oauth.json for setting the customUserAgent as a workaround.
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.
Package Metadata
Repository: codefiesta/OAuthKit
Homepage: https://codefiesta.github.io/OAuthKit
Stars: 32
Forks: 5
Open issues: 1
Default branch: main
Primary language: swift
License: MIT
Topics: github-api, google-api, ios, linkedin-api, macos, microsoft-azure, oauth, oauth-flow, oauth2, oauth2-authentication, oauth2-client, slack-api, slack-app, spm, swift, swift-package-manager, swiftui, tvos, visionos, xcode26
README: README.md