<- Back

What is OAuth 2.0

OAuth2 is an open standard protocol for authorization that enables secure and delegated access to a user's resources on different platforms without revealing their login credentials. It is widely used for third-party application authorization, allowing a user to grant limited access to their resources on a specific platform to an application without giving them their username and password.

OAuth2 works by using a three-party model consisting of the resource owner (the user), the resource server (the platform containing the user's resources), and the client (the application requesting access to the user's resources). The authorization process typically involves the following steps:

  • The client requests access to the user's resources on the resource server.
  • The resource server redirects the user to the authorization server to authenticate and authorize the request.
  • The user grants or denies access to the requested resources.
  • If the user grants access, the authorization server issues an access token to the client.
  • The client uses the access token to access the user's resources on the resource server.

OAuth2 supports various grant types as mentioned below

  • Authorization Code Grant: Used for web-based applications that require access to the user's resources. The client redirects the user to the authorization server, which generates an authorization code that the client exchanges for an access token.
  • Implicit Grant: Used for client-side applications that require access to the user's resources. The client requests an access token directly from the authorization server without an authorization code.
  • Client Credentials Grant: Used for server-to-server communication that does not involve user resources. The client sends its own credentials to the authorization server, which issues an access token to the client.

Detailed steps in OAuth2.0

here's a detailed explanation of each step involved in the Authorization Code Grant type of OAuth2:

  • Client requests authorization: The client application initiates the authentication process by sending a request to the Authorization Server (AS) to obtain authorization to access a protected resource on behalf of the user. The request includes the client's identity, the scope of access requested, and a redirect URI to which the AS will send the user back after authentication.

  • User authenticates with the Authorization Server: The AS authenticates the user, either by asking for their login credentials or by using a pre-existing session. If the user has not previously granted the client application authorization, they will be prompted to do so at this stage.

  • Authorization Server sends an authorization code: Once the user has successfully authenticated, the AS generates an authorization code and sends it to the client application via the redirect URI provided in step 1. The authorization code is a short-lived code that serves as a one-time password, and it is not the same as an access token.

  • Client requests access token: The client application exchanges the authorization code with the AS for an access token. The request includes the authorization code, the client's identity, and a client secret known only to the client and the AS.

  • Authorization Server sends access token: If the authorization code is valid, the AS sends back an access token to the client. The access token represents the client's authorization to access the requested resources and is usually long-lived. The response may also include a refresh token that can be used to obtain a new access token when the current one expires.

  • Client accesses protected resource: The client can now use the access token to access the protected resource on behalf of the user, by including it in API requests to the Resource Server (RS).

The Authorization Code Grant type provides several benefits like

  • improved security since the client never sees the user's credentials
  • the ability to support multiple authentication protocols
  • the ability to revoke access tokens.

Example

Let's see how this works when www.softpost.org wants to use the "Sign in with Google" feature.

Preresuisite :

  • You will need to go to google developer console https://console.cloud.google.com/apis/credentials
  • Then generate new credentials of type - OAuth 2.0 Client IDs
  • Then enter domain name of website and also enter callback url. e.g. e https://www.softpost.org/api/auth/callback/google or https://www.softpost.org/api/auth/callback/github if you want to use Github as auth server

Then write below code in /api/auth/[...nextauth]

import NextAuth from 'next-auth'
import AppleProvider from 'next-auth/providers/apple'
//import {CredentialsProvider} from 'next-auth/providers'
import EmailProvider from 'next-auth/providers/email'
import CredentialsProvider from 'next-auth/providers/credentials'
import GitHubProvider from 'next-auth/providers/github'
import GoogleProvider from 'next-auth/providers/google'
import { MongoDBAdapter } from '@next-auth/mongodb-adapter'
import MongoClientPromise from '../../../lib/mongodb'
//Request details: redirect_uri=http://localhost:3000/api/auth/callback/google
export default (req,res) => {

  let providerArray = getProviderArray()

  if (process.env.NODE_ENV==='production'){
    providerArray = providerArray.slice(0,-1)
  }


  return NextAuth(req,res, {
  adapter: MongoDBAdapter(MongoClientPromise),
  providers : [
    GitHubProvider({
    clientId :  process.env.githubClientId,
    clientSecret : process.env.githubClientSecret
    }),
    GoogleProvider({
      clientId :  process.env.googleClientId,
      clientSecret : process.env.googleClientSecret
      })],
  debug : true,
  secret : process.env.NEXTAUTH_SECRET,
  session:{strategy:'jwt'},
  jwt : {
  }
})
}
  • also make sure that NEXTAUTH_SECRET and NEXTAUTH_URL, googleClientId, googleClientSecret environment variables are set in env file.

Here are the steps that will be executed when user of www.softpost.org want to sign in using google.

  • User visits www.softpost.org and then click on sign in button. https://www.softpost.org/api/auth/signin/google
  • www.softpost.org (Client) will contact Google auth server to get authroization code. In some cases, resource server and and auth server can be same.
  • Google auth server will redirect user to google webpage. https://accounts.google.com/o/oauth2/v2/auth?client_id=9681438243-imkvauqm5ngmm3dsno16ue03fda.apps.googleusercontent.com&scope=openid%20email%20profile&response_type=code&redirect_uri=https%3A%2F%2Fwww.softpost.org%2Fapi%2Fauth%2Fcallback%2Fgoogle&state=C9IDcR-LvO8ZNIXme_plZ9n0kn7HtA6n_lQQLkZcFcI&code_challenge=InciAzBsXLGXO8eMxycmHoyqHfjdQt4UORTyJ1ZaQRE&code_challenge_method=S256
  • User will select the google account that he wants to sign in with and click on Allow
  • Auth server will send the authorization code to Client(www.softpost.org)
  • Client(www.softpost.org) will request access token from Auth server
  • Auth server will send access token back to client
  • Client will request user's data like email, profile picture, name etc from resource server using access token
  • Google resource server validates access token and responds with user's data

Web development and Automation testing

solutions delivered!!