Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A modern and observable framework for OAuth 2.0 authorization flows.

License

NotificationsYou must be signed in to change notification settings

codefiesta/OAuthKit

BuildSwift 6.2+Xcode 26.0+iOS 26.0+macOS 26.0+tvOS 26.0+visionOS 26.0+watchOS 26.0+License: MITCode Coverage

OAuthKit

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 Features

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:

OAuthKit Installation

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")]

OAuthKit Usage

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}}

OAuthKit Configuration

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.

OAuth initialized from main bundle (default)

@Environment(\.oauth)varoauth: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:

letoauth: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.

letproviders:[OAuth.Provider]=...letoptions:[OAuth.Option:Any]=[.applicationTag:"com.bundle.identifier",.autoRefresh:true,.useNonPersistentWebDataStore:true]letoauth: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 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)

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 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)

OAuthKit Authorization Flows

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)

OAuth 2.0 Authorization Code Flow

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)

OAuth 2.0 PKCE Flow

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)

OAuth 2.0 Device Code Flow

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)

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.

letgrantType:OAuth.GrantType=.clientCredentialsoauth.authorize(provider: provider, grantType: grantType)

OAuth 2.0 Provider Debugging

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.

OAuthKit Sample Application

You can find a sample application integrated with OAuthKithere.

Security Best Practices

  1. Use thePKCE workflow if possible in your public applications.
  2. 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.
  3. Don't includeoauth.json files 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.
  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 initiateClient 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 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 theencodeHttpBody 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 sampleoauth.json.
    • LinkedIn currently doesn't supportPKCE.
  • Instagram
  • Microsoft
    • Important: When registering an application inside theMicrosoft Azure Portal it's important to choose aRedirect URI asWeb otherwise the/token endpoint will return an error when sending theclient_secret in the body payload.
  • Slack
    • Important: Slack will block unknown browsers from initiating OAuth workflows. See sampleoauth.json for setting thecustomUserAgent as a workaround.
  • 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.

OAuthKit Documentation

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


[8]ページ先頭

©2009-2025 Movatter.jp