Implementing OAuth with ASWebAuthenticationSession
Learn about what OAuth is and how to implement it using ASWebAuthenticationSession. By Felipe Laso-Marsetti.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Implementing OAuth with ASWebAuthenticationSession
30 mins
- Getting Started
- Understanding OAuth
- Authorization Versus Authentication
- OAuth Roles
- The OAuth Flow
- Creating a GitHub App
- User Authorization Settings
- Post Installation Options
- Permissions Settings
- Viewing Your Results
- Connecting GitHub App with ASWebAuthenticationSession
- Updating the Project with GitHub App Values
- Views Overview
- View Models Overview
- Understanding ASWebAuthenticationSession
- Adding ASWebAuthenticationSession
- Checking for Errors
- Setting the Presentation Context Provider
- Starting the Authentication Session
- Handling the Authorization Code
- Displaying the Results
- Understanding Tokens
- Handling Tokens
- How NetworkRequest Handles the Tokens
- Creating Ephemeral Sessions
- Where to Go From Here?
User Authorization Settings
The next set of settings center around user authorization. The first option is the authorization callback URL. This is the page the authentication provider will redirect the users to when they successfully authenticate. The format you specify here is what your app will listen to, to take back control once a user authenticates.
Use the following for the app’s callback URL:
authhub://oauth-callback
This is just a callback you define. You can use a different value if you want, but note that it will change the setup process when working with ASWebAuthenticationSession. For now, it’s easiest to use the value above, so you can follow along.
The next option is a checkbox asking whether to let a user’s authorization tokens expire. Enable this checkbox because you want to acquire a refresh token and opt into expiring access tokens for a better security model.
Finally, there’s an option to request user authorization during installation, which can remain unchecked because you don’t need it for your app:
Post Installation Options
Moving down the page, there are post installation options and web hooks, which you can leave blank:
Be sure that the Active checkbox under Webhook is unchecked!
Permissions Settings
The next section relates to permissions. This is where you specify what information your app should be able to access.
In the Contents settings, change the access option to Read-only:
Finally, there’s a setting for where to install your app. For this example, select Only on this account:
Congratulations, you’ve configured your app. Now, click Create GitHub App and you’ll see your app’s details page.
Viewing Your Results
You’ve created an app in GitHub with its own app ID and client ID. Now you can set up a client — in this case, the AuthHub iOS app — to connect and use your GitHub app. If you had three different apps — perhaps iOS, Android and web — that connect to your GitHub app, you’d want to generate three different client secrets.
If you see a yellow banner at the top of the page telling you that you must generate a private key, click the link to do just that.
Next, click the Generate a new client secret button. Copy the alphanumeric value shown and paste it somewhere permanent because GitHub will never let you view this information again.
Be very careful about how you store your client secret and make sure you don’t share it.
You’re all done on the GitHub side. It’s time to write some Swift code!
Connecting GitHub App with ASWebAuthenticationSession
Download the project materials by clicking the Download Materials button at the top or bottom of the tutorial. Open the starter project in Xcode. Build and run.
Right now, tapping Sign In doesn’t do anything. You’ll need to implement the sign in feature in the project. Prior to doing that, you’ll explore the starter project.
You have a basic project with two screens: one to sign in and one to view your repositories. Also, you have models for User
, Repository
and NetworkRequest
.
The most interesting model here is NetworkRequest
. It acts as a wrapper around URLSession
.
Open NetworkRequest.swift. You’ll find enumerations that encapsulate the supported HTTP methods and errors for your network layer. The more interesting enum
here is RequestType
, which lists cases for the supported requests the app can make to GitHub. In the enumeration, you also have helper methods to construct a NetworkRequest
for a specific request type. Pretty handy!
For more information, check out GitHub’s documentation on its REST API.
Updating the Project with GitHub App Values
To let GitHub know about your app, you’ll add your GitHub app’s information to the project.
Open NetworkRequest.swift. Under // MARK: Private Constants
, you’ll find three static constants:
static let callbackURLScheme = "YOUR_CALLBACK_SCHEME_HERE"
static let clientID = "YOUR_CLIENT_ID_HERE"
static let clientSecret = "YOUR_CLIENT_SECRET_HERE"
Replace these values with the values from your newly created GitHub app.
The callback URL scheme doesn’t need to be the entire URL you entered when creating your GitHub app, it just needs to be the scheme. For this example, use authhub as the string for callbackURLScheme
.
Moving on, start(responseType:completionHandler:)
within NetworkRequest
is where the actual network request goes out. Here, you define some parameters for your URL request along with the authorization HTTP header, should your app have an access token available.
The GitHub API expects you to send the access token for requests that require authorization via the Authorization HTTP header. The value of this header will be in the format of:
Bearer YOUR_TOKEN_HERE
In addition, the method handles any errors with the completion handler and parses JSON data into a native Swift type specified in the parameters.
So far, so good!
Views Overview
Next, you have the views. This is a fairly simple app, so there are only two views necessary: SignInView.swift and RepositoriesView.swift. Not much to worry about here, the fun stuff happens in the view models.
Finally, you have the view models.
View Models Overview
Open RepositoriesViewModel.swift. This is where you’ll find code that requests a list of the logged-in user’s repositories from GitHub and provides them to the view to display in a list.
The other view model in the app is in SignInViewModel.swift. This is where you want to add your ASWebAuthenticationSession
. You’ll work on that now.
Understanding ASWebAuthenticationSession
ASWebAuthenticationSession
is an API that’s part of Apple’s Authentication Services framework and can be used to authenticate a user through a web service.
You create an instance of this class in order to acquire an out-of-the-box solution where you can point your app to an authentication page, allow the user to authenticate, and then receive a callback in your application with the user’s authentication token.
The cool thing about this API is that it’s going to adapt to the native platform it runs on. For iOS this mean an embedded, secure browser, and on macOS your default browser (if it supports web authentication sessions) or Safari.
With just a few parameters, you are up and running against your own (or third-party) authentication services, without having to implement everything from scratch using a web view.