A lightweight OAuth1 package for SwiftUI and using async/await.
Use this library to connect your users to services using the OAuth 1.0 standard for authorization. Simply initialize an OAuthManager
with the OAuthConfiguration
structure, which stores all the standard keys and URLs gathered from the service.
MGOAuth1 is available via Swift Package Manager
.
- Open your XCode project.
- Click file at the top of your screen.
- The second option down should be "Add Packages...".
- In the window that appears, search for either
MGOAuth1
orhttps://github.com/gannonmg/MGOAuth1
. - Select "Up to Next Major Version" and set the minimum to "1.0.2".
- Click "Add Package" at the bottom right of the screen.
- In the popup that appears, make sure the box next to MGOauth1 is selected.
- Click "Add Package" once more, and the package should be good to go!
- Create a new file and add
import MGOAuth1
to the top of it. - Create an instance of an
OAuthConfiguration
struct using the information provided to you by the service. For example, here is what it looks like when setting up access forDiscogs
.
import MGOAuth1
let config: OAuthConfiguration = .init(
client: "YourOAuthClient",
consumerKey: "abcxxxxxxxxxxxxxxx123",
consumerSecret: "xyzxxxxxxxxxxxxx789",
callback: "your_oauth_app://oauth-callback/discogs",
callbackScheme: "your_oauth_app",
requestTokenUrl: "https://api.discogs.com/oauth/request_token",
authorizeUrl: "https://www.discogs.com/oauth/authorize",
accessTokenUrl: "https://api.discogs.com/oauth/access_token"
)
- It is recommended not to commit this file to ensure the keys remain secure.
- In a high level view in your app, create an
OAuthObservable
object using the configuration set up in the last step. This object can be passed along as anObservableObject
orEnvironmentObject
as needed. - Add the
.oAuthSheet(oAuthObservable: OAuthObservable)
modifier to your view. - Add a login button that calls
OAuthObservable.authorize()
OAuthObservable
should handle the rest! It will pop a sheet, authorize your user, and store their access credentials for your app to use.
import MGOAuth1
struct ContentView: View {
@StateObject var oauthObsv: OAuthObservable = .init(config: config)
var body: some View {
VStack {
if oAuthObservable.isLoggedIn {
Text("Pretty easy, right?")
} else {
Button("Authorize") {
oAuthObservable.authorize()
}
}
}
.oAuthSheet(oAuthObservable: oAuthObservable)
}
}
In just a few lines of code, you now have an authorized user via OAuth!
To make an authorized request, simply call your target like so:
let user: User = try await oAuthObservable.manager.get(from: "https://api.discogs.com/oauth/identity")
At the moment, only get
requests are supported. I do plan on updating to include more HTTP Methods, however, it is low on my priorities. It should be a fairly simple add, so if anyone would like to fork the repository and submit a pull request, be my guest!