Everything you need to know about OAuth

Everything you need to know about OAuth

Understand OAuth in detail and build a website adding GitHub OAuth using Appwrite while at it!

Nowadays, Authentication has become an inseparable part of applications. You can opt for many ways to authenticate users to your website (email/password being the most commonly used). But one of the most convenient and my personal favorite <3 is OAuth.

Now, let me take a moment to convince you why you should choose OAuth👀:

  1. Single Account, Multiple Platforms: Users don't have to juggle between a gazillion passwords anymore, instead they can easily log in with their existing accounts like Google or Facebook. Hence, no need to create new accounts :)

  2. Gain access to User's Resources🫣: OAuth comes with an additional perk, that lets you access certain users' resources (be it their data or some kind of functionality), in the most secure and trustworthy way possible.

So there you have it. OAuth not just comes in handy for verifying the user - Authentication, but also for getting the user's permission to access certain resources - Authorization!


But wait, how is this all happening?

For my curious tinkling minds out there, don't you wanna know how things work behind the scenes?

Prerequisites:
OAuth, or OAuth2 (the latest version of OAuth) in particular, operates based on the concept of "tokens". You can think of these tokens as access tickets, which serve as temporary authorization keys. These tokens are short-lived and revocable.

Terminology:

  • Resource Owner: The user

  • Client: The client app

  • Resource Server: The one that hosts the protected user accounts.

  • Authorization Server: The one that verifies the identity of the user

Okay, let's get into some serious geeky stuff🤓(in the most non-geeky way><)

  1. Stirring up: User chooses to sign in with Google on a third-party app. The app says, "Wait a minute, let me ask Google first" and sends an authorization request.

  2. Who you?: Google authentication window pops up, asking the user to log in. "Are you really you?", it asks.

  3. The Handshake: Once logged in, Google asks the user, "Hey, this app wants to access your info, you cool with that?" If the user agrees, Google hands over an authorization grant (think of it as a proof of consent).

  4. Passing the Secret Note: The client app takes this grant, sends it back to Google along with its ID and secret.

  5. The Magic Key: If Google validates the grant and credentials, it presents the app with an access token, like a magical key.

  6. Success!: With the magic key (access token), the app can now ask Google for user information as needed. Access granted!

(Disclaimer: Light mode is preferred for the diagram)

Well, I hope now you know what's going on in the background, when you click that "Sign in with Google" button😉.

Now, let's add a cherry on the top by actually adding OAuth in our app🍰.


This is what we'll be building

A website that not only logs in users with their GitHub account but also tries to get their GitHub info, all with ReactJS and Appwrite❤️

Click to visit website

First things first...

Clone this repo and checkout to template branch and npm i in the terminal. Now that we have a starting template, we are good to go (you can npm start as well, and don't fret if you are greeted by a bunch of errors😬).

Let's take a quick look at the file structure before we get started:

src/
├── appwrite/
│   └── Appwrite.js
└── components/
    ├── Landing.jsx
    ├── Success.jsx
    └── Failure.jsx

You Ready?

This is what we're gonna do, we will break the whole process into 3(or maybe 4) simple steps👇

Step: 0 -> Create an Appwrite project

Step: 1 -> Register an OAuth app

Step: 2 -> Enable the OAuth provider

Step: 3 -> Add code

So, without further ado, let's get coding🤓🚀

Step: 0

Creating Appwrite project

Go to Appwrite cloud. Create a new account. Create a new project. In the settings, you will see projectID and project endpoint, copy it and add it to your appwrite.js file.

client
  .setEndpoint("https://cloud.appwrite.io/v1") // Your Appwrite Endpoint
  .setProject("[PROJECT_ID]");         // Your project ID

Basically: Create new account > create new project > set client

Hold on, breaks🚗💨! What did we do just now? So we created an Appwrite client which is required for making any calls to the Appwrite API.

Step: 1

Registering an OAuth app

Go to your GitHub. Go to developer settings. Click on OAuth apps. Register a new OAuth app.

And fill up these details:

  • Application name: anything

  • Homepage URL: anything (eg: GitHub repo link)

  • Application description: anything

  • Authorization callback URL: from step- 2

Basically: GitHub settings > developer settings > OAuth apps > new OAuth app

Just FYI, the OAuth app is required to establish a secure connection between our application (the client) and the service provider's API.

Step: 2

Enable OAuth provider

Go back to the Appwrite console. Go to Auth settings. Enable GitHub. Copy the URI provided there back to the Authorization callback URL in step 1. You will get a Client ID and a Client secret, paste them back in the App ID and App Secret field respectively, in the console. Finally, click update.

Basically: Auth > Settings > GitHub > Toggle enable > Set callback URL > Set app ID and secret > Click update

Step: 3

Add code

Firstly, we have this register function, that gets triggered when the user clicks on continue with GitHub. All we need to do is call the createOAuth2Session endpoint here.

It takes three parameters:

  • Provider name(in our case GitHub)

  • Success URL(user's redirected here, if everything goes well)

  • Failure URL(if authentication fails, the user is redirected here)

register: async (success, failure) => {
    // Register by creating an OAuth2 session
    account.createOAuth2Session("github", success, failure);
  }

Now, go ahead and try it out. You will notice a new user is added to your Appwrite console😊.

DISCLAIMER: Make sure you have cookies enabled in your browser

Yes! Adding OAuth is that easy. But hold on, let's take an additional step and try to get all the info we can, about our user👀.

  • Getting their account info👇

    Appwrite creates a new account in the database when it's a new user!

      getAccount: async () => {
          //get account data
          return await account.get();
        }
    
  • Getting their session info👇

    A new session is assigned to a user, every time they log in!

      getSession: async () => {
          //get current session data
          return await account.getSession("current");
        }
    
  • Getting their GitHub info👇

    If you noticed, in the session details, we got a provider access token. And yes, this is exactly the access token I was talking about earlier!

      getGithubData: async () => {
          //get user's provider access token
          const promise = await account.getSession("current");
    
          const providerAccessToken = promise.providerAccessToken;
          //make a request to github api
          const response = await fetch("https://api.github.com/user", {
            headers: { Authorization: `token ${providerAccessToken}` },
          });
          return await response.json();
        },
    
  • Logging out👇

    Some wise person once said(that's me😆), with logging in comes logging out. So why not see how to log out as well?

      logout: async () => {
          // Delete the session
          await account.deleteSession("current");
        }
    

We did it! That was easy peasy!

You can also play around with other OAuth providers (Appwrite supports some 30+ providers😳), the steps are similar. These are the docs you can refer to.


That's all folks!

I hope you had fun and learned something new today. Don't forget to connect with me.

See you on the next one!!


❤️Follow me on Twitter to know more about me!

💕 Also subscribe to my Youtube Channel!