In this article, we'll go over some of the fundamentals of OAuth2 in detail about the Integration platform. The goal is to show how this well-known OAuth Node.js protocol works behind the scenes, with Node.js thrown in for good measure.

About OAuth2.0

When it comes to understanding what OAuth is all about, there are a lot of misconceptions and over-complications.OAuth2 has a few predefined flows that you can use in your projects, but some of them will not be applicable to your situation. In this section, we'll show how the interested party who owns the web application in development (in this case, you) uses a third-party system to infer authorization within the application. Consider the big names in third-party systems, such as Google, Facebook, or, in our case, GitHub.

Authorization Upon Facebook’s Systems

The most common OAuth2 flow is typically divided into three major steps: In this blend of processes as we consider OAuth Node.js together.

  1. Your app opens a new window for the third-party authorization app, asking the user (who must have an account and be logged in on the system based on account) to grant permission for your app to take action on his/her behalf.

  2. The third-party app acknowledges the permission and redirects the user back to your app via a pre-configured URL once properly authenticated and authorized.

  3. Your application exposes an endpoint for such callback operations and uses the response code returned by the previous redirect process to request an access token from the third-party provider API.

  4. If you do not want to delegate the process of storing users' login information and prefer to handle authorization yourself, you can set up an OAuth2 server as part of OAuth API.

Because of the number of customizations required to meet their needs, many businesses today do this for convenience. Let's take a closer look at this scenario and see how Node.js handles it in this blended mode of OAuth Node.js

Basic Environment Setup

In this context we'll be using Node.js and Yarn as the default package manager for this OAuth Node.js setup in this article. Node.js is currently running version-v12.21.0. However, most versions greater than 10 should be working fine for this OAuth Node.js blend setup.

During the head start make sure to complete all of the official installation steps in case you still require this OAuth Node.js blend to be started from scratch.

For this write-up, we'll build two apps: one for the client (in React API) and one for the server capabilities as part of the API Integration using specific applications.

It's important to note that, while you can build your OAuth2 server from scratch using frameworks like node-oauth2-server, we'll use GitHub's capabilities for the sake of simplicity of work.

As such there are too many details surrounding the ability to properly set up an OAuth Node.js server that we will not cover for the time being in this blog.

However, if you want to take the plunge, the server project we'll create will be more than adequate for the role of OAuth2's server host.

GitHub App Config

We'll be using the powerful GitHub OAuth2 API for this tutorial. GitHub lets you create an app under your account and provides you with OAuth2 client credentials to use in other apps.

This way, users of your application can easily log in using their GitHub accounts.

So, let's start by clicking this link and making a new application. Fill out all of the fields appropriately

Register a New OAuth application

The most important field is the Authorization callback URL, which specifies where GitHub should redirect the user once the authorization process is complete.

Please keep in mind that you can enter any URI you want. When you click the Register application button, you may see a screen that displays the Client ID and your Client secrets.

Client ID and Secrets Associated With Maintaining

When you arrive here, click the button to generate a new client secret. Before leaving this screen, copy/paste it somewhere safe because you won't be able to see it again in the future.

The Server Project

Let's get back to work on the project. Select a folder and execute the key command.

Again, leave all of the options as presented until the end. Then, run the command below to install the necessary NPM dependencies.

HTTP request calls to the GitHub OAuth2 servers will be made using Axios. Express will be our server, and cors will only be used to avoid conflicts with the browser's Same-Origin policies.

The server code is very simple and can be found in widely available code. Make sure to include it in a file called index.js.

Once the authorization steps are completed, we simply proxy requests from the GitHub platform to the /oauth/redirect path on this server.

When it's finished, we must call it again to obtain a valid access token. GitHub needs to know who is calling in order to determine whether the caller has such access.

The only way GitHub knows this is through the client id and client secret provided by your GitHub application, which can be passed as request parameters.

Also, keep in mind that we're passing a query parameter called code that GitHub provides when calling the callback URL as a secondary security check. Otherwise, the request would be rejected.

If the second GitHub call succeeds, we can route the response and all of its content to the React client application listening on port 3000.

Before proceeding to the next section, run the following command to ensure that everything is in working order:

node index.js, which may result in the following output:

Port 8080 is open for listening.

The Client Project

To make things look cleaner, React and Bootstrap will be used on the client project.

To create the client project, leave the current server folder and run the following command

npx oauth2-node-app create-react-app

We're also using the create-react-app tool to make things easier for the client. After running it, make sure to leave all of the options at their default settings until the end.

Then, execute the following command to include the necessary Node dependencies:

yarn include the react-bootstrap axios

To inject Bootstrap's styles into the React project, include the following CSS import in your index.js file:

Great! import 'bootstrap/dist/css/bootstrap.min.css'; Without further ado, let's proceed and replace the following content in your App.js file:

We'll use only React hooks for the entire implementation because we're using the most recent version of React (17.0.1).

Let’s Break It Down a Little More for Better Clarity

  1. First, we use the usestate hook to create two state objects: a Boolean to determine whether the user is logged in and a user object to store the response from GitHub. Both with the appropriate setter methods.

  2. Then, we set up a use effect hook to load only once when the entire component page is loaded and check for the user's details using the query param access token. If the parameter is present, let's set the user and loggedIn state values so that the logic to render the component takes them into account. Otherwise, we just show the Sign-up component.

  3. The render function displays the appropriate component based on the current authorization state. We won't go into detail about how React components work here, but feel free to replace them with as much Bootstrap goodness as you want.

  4. It's worth noting that we're giving GitHub the URL for the client id on the button. Make sure to replace it with your own.

You may have also noticed a third localhost URL on this code list: http://localhost:8010/proxy/user. The reason for this is that attempting to access GitHub directly from the UI will result in some cors-related issues.

The simplest solution is to set up a local proxy to handle the cors domain conversions for us. The local-cors-proxy NPM module is ideal for this task.

auth-nodejs-oauth

To install it globally, simply run the following command:

  • install npm -g local-cors-proxy

  • Then, in the same terminal window, issue the following command to start it:

  • https://api.github.com/lcp —proxyUrl

  • The output indicates that everything went well:

  • The cors proxy server is being started.

  • It provides you with a port at localhost (typically 8010) to proxy to that specific URL.

Adding Some Style

Before we begin the tests, we must also add some styling. Since we already have an index.css file with some CSS styles, let's change its content to

Testing

In the client's root folder, run the following command to test the client implementation:

start npm

Examine the logs for errors and wait for React to load the application in your web browser.

The Sign in button may take you to the following screen. Before you click it, make sure that both the server app and the proxy are running.

Log in using GitHub.

You'll be redirected to the GitHub authorization page after clicking the Sign in button, as shown in the image below.

GitHub authorization page.

If you are not properly logged in, GitHub will handle the entire authentication flow for you. One of the many advantages of this approach is the ability to delegate user authentication.

When you click the Authorize button, GitHub will handle the redirecting process for you. Finally, you might see the following screen

Welcome page with GitHub user information.

Another test you can perform immediately after is to return to the root URI and click the Sign in button. You may notice that the login process runs smoothly without an authorization page because, once authorized, the state of the authorization persists until you revoke it.

github-oauth-api

Wrapping Up

The source code for this tutorial can be found here.

Many new developers complain that OAuth2 is overly complicated and too difficult for them to handle. The protocol is lengthy, but you don't have to go through it all at once.

Many aspects of the protocol are rarely used. Begin with the basics and work your way up in small but manageable steps.

There's more to learn about it, such as scopes, authorities, and permissions, 2FA. As a next step, consider storing these access tokens in a database for the server project and in your browser's local storage for the client part. It would be ideal for your users if they could close the browser and return later to find that the session is still active.

Know Why Applet.io is the Best App Widgets Software!
Join the SaaS Revolution
ribbon
  • All-in-One Suite of 50 apps

  • Unbelievable pricing - ₹999/user

  • 24/5 Chat, Phone and Email Support

Tags

Email Finder Author Finder Email Validator Email List Email Hunter Email Checker Email Lookup Email Extractor Email Address Finder Email Scraper Find Emails CRM Software CRM Sales CRM CRM Software Enterprise CRM Software Cloud CRM Software Sales Enablement Workflow Automation Retail CRM Call Center CRM Real Estate CRM Sales Tool SDR Software Sales Engagement Platform Sales Qualified Leads Lead Management Tool Sales Tracking Sales Automation Outbound Sales Sales Prospecting Follow Up Leads Lead Management Call Center Software Call Center Software Outbound Call Center Auto Dialer Software Dialer Call Monitoring Automatic Call Distributor Answering Machine Detection Cloud Contact Center Software Virtual Call Center Call Management Time Tracking Time Tracking Employee Monitoring Time Tracker Time Tracking Software Timesheet Employee Time Clock Employee Tracking App Timekeeping Tracking App Time Clock App Applicant Tracking System ATS Applicant Tracking System Application Tracking System Applicant Software Recruiting Software ATS System Applicant Tracking Applicant Tracker Recruitment Software Candidate Relationship Management Systems Video Interviews Assessment Management Recruitment Software Video Interview Virtual Interview Coding Interview Interview Tool Online Assessment Employment Assessment Test Position Management Hiring App HRMS Software Human Resource Management HRMS Software HR Software Payroll Software Human Resource Software Employee Onboarding HRMS HR System Employee Management Document Management AI Writer Lead Enrichment AI Email Writer Sales Pitch Writer AI LinkedIn Outreach SEO Email writer Backlink Email Writer LinkedIn Chrome Extension Opening Line Writer Lead Generation Linkedin Search Email Finder Prospect Lead Generation Sales Generation Data Enrichment CRM Integrations Technology Search Search with Email Integrations Website Search OKR Tool KPI OKR Task Management Performance Review Employee Performance Evaluation Employee Review Performance Management System OKR Goals MBO Email Notifications Learning Management System LMS Elearning Enterprise Learning Management Professional Development Employee Training Learning Management System Learning Platform Asynchronous Learning Training Management Knowledge Management Chatbot Chatbot AI Chatbot Customer Service Chatbot Online Chatbot Create Chatbot Messenger Chatbot Chatbot Software Website Chatbot Software Survey Bot Bot Builder Help Desk Software Ticketing Tool User Experience Help Desk Software Ticketing System Helpdesk Ticketing System Feedback Management Service Desk Software Support Ticketing Software Helpdesk Support Software Customer Service Ticketing System Live Chat Customer Service Software Live Chat Software Live Chat App Live Chat System Website Live Chat Live Chat Tool Web Chat Software Live Chat Support Software Customer Service Tool Live Chat Service Customer Feedback Customer Feedback Survey Customer Feedback Management Software Feedback Management Tool Customer Satisfaction Survey Software Customer Feedback Management System Client Feedback Software Survey Analysis Feedback Survey Software Feedback Management System User Feedback Software Customer Onboarding Customer Success Management Onboarding Process Workflows Customer Retention Customer Journey Onboarding Checklist User Segmentation Personalization Customized Templates Popup Builder API Platform End To End API Management Unified API Control REST API Management Web API Gateway API Documentation API Management API Integration API Development Unlimited Projects API Gateway Single Sign on Authentication Software Application Management Password Management SSO Configuration SSO Single Sign-On Access Management Easy Set-Up Single Login Secure Login App Builder App Builder Platform Low Code Application Platforms Low Code Development Build Your Own App Low Code App Software Drag And Drop Builder Custom Application Low Code Platform Low Code No Code Bespoke Software App Widgets Custom Widget File Picker Playground OAuth Keys File Manager Website Monitoring Reporting Web Application Monitoring Website Monitoring App Monitoring Performance Monitor App Baseline Analysis Location Insights Alerting System Reporting Wireframe Tool Multi-Channel Notifications Design UI UX Project Management Mock Designer Wireframe Designer Website Mockup UI Prototyping Image Library Project Management Real-Time Updates Design UI UX Website Builder Website Builder Webpage Builder Website Creator Landing Page Creator Website Maker Blog Builder Ecommerce Website Builder Website Analytics Website Development Landing Page Builder Email Marketing Email Marketing Software Bulk Email Sender Automated Email Email Campaign Systems Email Automation Software Autoresponders Email Blast Service Email Marketing Email Marketing Automation Drip Campaigns Social Media Management Instagram Post Scheduler Social Media Analytics Social Media Management Social Media Planner Social Media Calendar Social Media Scheduling Social Media Listening Social Media Monitoring Social Listening SEO Tool Keyword Tool Link Building SEO Optimizer Website Audit On-Page SEO Broken Link Checker Rank Tracker Website Grader SEO Competitor Analysis Website Recording Website Analytics Click Tracking Usability Testing Website Monitoring Mouse Tracking Visitor Recording Session Replay Conversion Funnels Website Recording Website Visitor Tracker Website Personalization Lead Generation Tool Popup Maker Lead Generation Software Popup Builder Website Personalization Software Lead Capture Software Popup Builder Lead Capture Tool Lead Generation App Website Personalization App Content Planner Content Planner AI Writer Social Media Content Planner Ai Content Writer Social Media Content Calendar Content Generator AI Blog Writer Content Marketing Software Social Media Calendar Social Media Planner Push Notification Push Notification Push Messages Push Notification Service Push Service Push Notification App Custom Notifications Mobile Push Notifications Push Notification For Website Push Notification Tool Push Notification Providers Image Personalization Email Marketing Template Countdown Clock Personalization Software Personalized Software Countdown Clock Countdown Timer In Email Personalization Tool Personalized Images Personalized Videos Conversational Chatbot PPC Management Keyword Research PPC Management PPC Marketing Keyword Finder Keyword Generator Shopping Ads Adwords Reports Keyword Research Tool Keyword Suggestion Tool Team Chat Team Chat Software Collaboration Software Team Collaboration Team Communication Online Collaboration Collaboration Tool Teamwork Collaboration Virtual Communication Team Collaboration Software Business Phone System Virtual Phone Numbers Virtual PBX Toll Free Numbers Business Phone System IVR PBX Small Business Phone System PBX System VoIP Phone Cloud Phone Video Conferencing Video Conferencing Video Call Recording Virtual Conferencing Software Virtual Meetings Virtual Meeting Platforms Virtual Conference Platforms Online Conference Platforms Video Calling Software Cloud Meetings Video Conferencing Software Email Provider Email Software Software For Emails Hosted Emails Email With Domain Custom Email Address Email Hosting Business Email Address Email Encrypted Custom Domain Email Project Management Software Project Management Task Management Project Planner Project Management Tool Task Management Software Project Planning Software Project Management App Task Management App Project Management System Project Management Software Form Builder Form Builder Survey Builder Order Forms Web Forms Form Maker Form Creator Form Designer Survey Maker Survey Creator Custom Form Appointment Scheduling Appointment Scheduling Software Appointment Scheduling System Meetings Scheduler Appointment Scheduling App Online Appointment Scheduling Online Scheduling App Appointment Scheduler Appointment Booking App Calendar Scheduler Online Scheduler Robotic Process Automation RPA Tools RPA RPA Automation Robotic Automation Software Data Scraper Web Scraper Robotic Automation Website Scraper Business Process Automation Robotic Process Automation Business Process Management Workflow Management Business Process Modelling Business Process Automation BPMN BPM Software BPM Tool Business Process Management Workflow Software Workflow Automation Business Process Mapping App Integration Workflow Software Workflow App Workflow Automation Process Automation Application Integration Data Integration Tool Workflow Management Software Data Integration Software Workflow Tool Marketing Automation Electronic Signature Signature Maker Digital Signature Software Digital Signature Pdf Signer Esign Online Signature Signature Creator Sign Documents Online Electronic Sign E Signature

Get Started with 500apps Today

Applet.io is a part of 500apps Infinity Suite

Please enter a valid email address
Sign Up 14-day Trial