Newbies to OAuth can find it tricky initially. In this tutorial you’ll learn how to get started with OAuth 2.0 while avoiding all the fiddly parts around handling tokens. The folks over at Insomnia will show you how to authenticate an API client for the GitHub APITrack this API with OAuth 2.0 and the Insomnia app. You’ll then be able to create a GIT repo via the API once you’re done.
Gathering OAuth Credentials
To start, you’ll need to fetch the Client ID, Client Secret and Callback URL when you register your OAuth app with Github here. The callback URL is optional. Lastly, you’ll need the Authorization URL and Access Token URL. These are listed in the Github API docs.
Setting Up The Request
You’ll now create a repository endpoint to demonstrate the power of OAuth. To get started, open Insomnia and create a request named ‘Create Repository’. Then copy and paste the following curl command into the URL bar:
Setting Up OAuth 2.0
Now, if you tried to send that request, you’d get a 401 unauthorized error. You need to send an OAuth token with the request for it to work. Getting the right OAuth token for your API client can be tricky. So we’ll use Insomnia to manage the OAuth tokens for us. So select the Auth tab of your ‘Create Repository’ request and change authentication type to ‘OAuth 2’. Now you’ll add those credentials you collected from GitHub at the beginning.
Sending The Request
Now OAuth is set up, you’re able to send your request. Insomnia will see that you don’t have the right token and will start the authentication process for you. It’ll prompt you to give your GitHub creds and then will do the authorization for your app. The token will be stored in Insomnia and sent with the request to GitHub. After sending, you should see a ‘201 Created’ response with info about the new repo.
Learning More About OAuth 2.0
If you go to the Timeline tab in the Insomnia app, you can view the Authorization header sent with the request. There you can see the token after ‘Bearer’ that Insomnia obtained during login. If you want to get rid of this token or get a new one, you can do this in the Auth tab of the request in Insomnia.
Some OAuth 2.0 APIs have expiring or refresh tokens. If an API token has an expiry date, this will show at the bottom of the Auth tab. When the token expires, Insomnia will refresh the token with your next request so you don’t have to. You can also refresh it yourself manually.
For the GitHub API we used an ‘Authorization Code’ grant type. Keep in mind that OAuth 2.0 has four grant types that can be used in different contexts to fetch tokens. The other three are Client Credentials, Implicit and Resource Owner Password Credentials.
You now know how to get started with OAuth 2.0 APIs. Nearly everything you learned for GitHub can be transferred to other APIs.