- Notifications
You must be signed in to change notification settings - Fork3
A modern and observable framework for OAuth 2.0 authorization flows.
License
codefiesta/OAuthKit
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation

OAuthKit is a contemporary, event-driven Swift Package that utilizes theObservation Framework to implement the observer design pattern and publishOAuth 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 is a small, lightweight package that provides out of the boxSwift Concurrency safety support andObservable 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
OAuthKit can be installed usingSwift Package Manager. If you need to build with Swift Tools6.1 and Apple APIs >26.0 use version1.5.1.
dependencies:[.package(url:"https://github.com/codefiesta/OAuthKit", from:"2.0.0")]
The following is an example of the simplest usage of using OAuthKit across multiple platforms (iOS, macOS, visionOS, tvOS, watchOS):
import OAuthKitimport SwiftUI@mainstructOAuthApp:App{@Environment(\.oauth)varoauth:OAuth /// Build the scene bodyvarbody:someScene{WindowGroup{ContentView()}#if canImport(WebKit)WindowGroup(id:"oauth"){OAWebView(oauth: oauth)}#endif}}structContentView:View{@Environment(\.oauth)varoauth:OAuth#if canImport(WebKit)@Environment(\.openWindow)varopenWindow@Environment(\.dismissWindow)privatevardismissWindow#endif /// The view body that reacts to oauth state changesvarbody:someView{VStack{switch oauth.state{case.empty: providerListcase.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){ _, stateinhandle(state: state)}} /// Displays a list of oauth providers.varproviderList:someView{List(oauth.providers){ providerinButton(provider.id){authorize(provider: provider)}}} /// Starts the authorization process for the specified provider. /// - Parameter provider: the provider to begin authorization forprivatefunc authorize(provider:OAuth.Provider){#if canImport(WebKit) // Use the PKCE grantType for iOS, macOS, visionOSletgrantType:OAuth.GrantType=.pkce(.init())#else // Use the Device Code grantType for tvOS, watchOSletgrantType: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 changeprivatefunc handle(state:OAuth.State){#if canImport(WebKit)switch state{case.empty,.error,.requestingAccessToken,.requestingDeviceCode:breakcase.authorizing,.receivedDeviceCode:openWindow(id:"oauth")case.authorized(_, _):dismissWindow(id:"oauth")}#endif}}
By default, the easiest way to configure OAuthKit is to simply drop anoauth.json file into your main bundle and it will get automatically loaded into your swift application and available as anEnvironment property wrapper. You can find an exampleoauth.json filehere. OAuthKit provides flexible constructor options that allows developers to customize how their oauth client is initialized and what features they want to implement. See theoauth.init(_:bundle:options) method for details.
@Environment(\.oauth)varoauth:OAuth
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:
letoauth:OAuth=.init(.module)
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.
letproviders:[OAuth.Provider]=...letoptions:[OAuth.Option:Any]=[.applicationTag:"com.bundle.identifier",.autoRefresh:true,.useNonPersistentWebDataStore:true]letoauth:OAuth=.init(providers: providers, options: options)
To support custom protocols or URL schemes that your app supports, developers can pass a custom.urlSession option that will allow the configuration of customURLProtocol classes that can handle the loading of protocol-specific URL data.
// Custom URLSessionletconfiguration:URLSessionConfiguration=.ephemeralconfiguration.protocolClasses=[CustomURLProtocol.self]leturlSession:URLSession=.init(configuration: configuration)letoptions:[OAuth.Option:Any]=[.urlSession: urlSession]letoauth:OAuth=.init(.main, options: options)
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 defaultLAContext, but if you need fine-grained control while evaluating a user’s identity, pass your own customLAContext to the options.
Developers can also implement private browsing by setting the.useNonPersistentWebDataStore option to true. This forces theWKWebView used during authorization flows to use a non-persistent data store, preventing data from being written to the file system.
// Custom LAContextletlocalAuthentication:LAContext=.init()localAuthentication.localizedReason="read tokens from keychain"localAuthentication.localizedFallbackTitle="Use password"localAuthentication.touchIDAuthenticationAllowableReuseDuration=10letoptions:[OAuth.Option:Any]=[.localAuthentication: localAuthentication,.requireAuthenticationWithBiometricsOrCompanion:true,.useNonPersistentWebDataStore:true,]letoauth:OAuth=.init(.main, options: options)
OAuth 2.0 authorization flows are started by calling theoauth.authorize(provider:grantType:) method.
A good resource to help understand the detailed steps involved in OAuth 2.0 authorization flows can be found on theOAuth 2.0 Playground.
oauth.authorize(provider: provider, grantType: grantType)
TheAuthorization 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 thePKCE extension with this flow as well to provide better security.
// Generate a state and set the GrantTypeletstate:String=.secureRandom(32) // See String+ExtensionsletgrantType:OAuth.GrantType=.authorizationCode(state)oauth.authorize(provider: provider, grantType: grantType)
PKCE (RFC 7636) is an extension to theAuthorization 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 objectoauth.authorize(provider: provider)// Or you can specify the workflow to use PKCE and inject your own valuesletgrantType:OAuth.GrantType=.pkce(.init())oauth.authorize(provider: provider, grantType: grantType)
OAuthKit supports theOAuth 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 thedeviceCodeURL to yourOAuth.Provider.
letgrantType:OAuth.GrantType=.deviceCodeoauth.authorize(provider: provider, grantType: grantType)
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.
letgrantType:OAuth.GrantType=.clientCredentialsoauth.authorize(provider: provider, grantType: grantType)
Debugging output withdebugPrint(_:separator:terminator:) into the standard output is disabled by default. If you need to inspect response data received fromproviders, you can toggle thedebug value to true. You can see anexample here.
You can find a sample application integrated with OAuthKithere.
- Use thePKCE workflow if possible in your public applications.
- Never check inclientID orclientSecret values into source control. Although theclientID is public and theclientSecret is sensitive and private it is still widely regarded thatboth 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 toinspect 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 initiateClient Credentials workflows since it is possible for someone to extract your secrets.
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 ourhere.
- Auth0 / Okta
- Box
- Dropbox
- Github
- Google
- Important: When creating a Google OAuth2 application from theGoogle 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
encodeHttpBodyproperty 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 sampleoauth.json. - LinkedIn currently doesn't supportPKCE.
- Important: When creating a LinkedIn OAuth2 provider, you will need to explicitly set the
- Microsoft
- Important: When registering an application inside theMicrosoft Azure Portal it's important to choose aRedirect URI asWeb otherwise the
/tokenendpoint will return an error when sending theclient_secretin the body payload.
- Important: When registering an application inside theMicrosoft Azure Portal it's important to choose aRedirect URI asWeb otherwise the
- Slack
- Important: Slack will block unknown browsers from initiating OAuth workflows. See sampleoauth.json for setting the
customUserAgentas a workaround.
- Important: Slack will block unknown browsers from initiating OAuth workflows. See sampleoauth.json for setting the
- Stripe
- Twitter
- Unsupported: Although OAuthKitshould work with Twitter/X OAuth2 APIs without any modification,@codefiesta has chosen not to support anyElon 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.
You can find the complete Swift DocC documentation for theOAuthKit Framework here.
About
A modern and observable framework for OAuth 2.0 authorization flows.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.
