OAuth 2.0 and JWT Authorization in JavaScript: A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why OAuth 2.0 and JWT Are the Standard for Modern Authorization



In modern web development, secure user authentication and authorization are key tasks. The two most popular protocols and formats that solve this problem are OAuth 2.0 and JWT (JSON Web Token). Although they are often used together, they are different things: OAuth 2.0 is an access delegation protocol, while JWT is a token format.



In this article, we will break down how OAuth 2.0 works, what JWT is, and how to implement them in JavaScript (Node.js). The material is aimed at beginner developers, so we will move from theory to practice with clear code examples.



What is OAuth 2.0 and How It Works



OAuth 2.0 (Open Authorization) is a protocol that allows an application to obtain limited access to a user's resources without sharing their login and password. Imagine you want to log into a website via Google or GitHub — that is OAuth 2.0.



Main Roles in OAuth 2.0

  • Resource Owner — the user who owns the data
  • Client — the application requesting access
  • Authorization Server — the server issuing tokens (e.g., Google)
  • Resource Server — the server storing the user's data


Authorization Code Grant Flow (Node.js Example)

The most common and secure OAuth 2.0 flow is the Authorization Code Grant. Let's look at its implementation using Express.js.



// Installing dependencies// npm install express axios dotenv

// .envCLIENT_ID=your_client_idCLIENT_SECRET=your_client_secretREDIRECT_URI=http://localhost:3000/callback


const express = require('express');const axios = require('axios');require('dotenv').config();

const app = express();

// Step 1: Redirect the user to the authorization pageapp.get('/auth', (req, res) => { const authUrl = `https://provider.com/oauth/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=${process.env.REDIRECT_URI}&response_type=code&scope=email`; res.redirect(authUrl);});

// Step 2: Handle the callback with the authorization codeapp.get('/callback', async (req, res) => { const { code } = req.query;

try { // Exchange the authorization code for an access token const tokenResponse = await axios.post('https://provider.com/oauth/token', { client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, code, redirect_uri: process.env.REDIRECT_URI, grant_type: 'authorization_code' });

const { access_token, refresh_token } = tokenResponse.data; // Save the tokens (in a real project, save to a database) req.session.accessToken = access_token; req.session.refreshToken = refresh_token;

res.send('Authorization successful!'); } catch (error) { res.status(500).send('Authorization error'); }});

app.listen(3000, () => console.log('Server running on port 3000'));


JWT (JSON Web Token): Structure and Creation



JWT is a compact and self-contained way to transmit information between parties as a JSON object. The token consists of three parts separated by dots:



  • Header — the token type and signing algorithm (e.g., HS256)
  • Payload — the data (claims) we want to transmit
  • Signature — the signature ensuring data integrity


Creating a JWT in Node.js

To work with JWT, we will use the jsonwebtoken library.



// npm install jsonwebtoken

const jwt = require('jsonwebtoken');

const secretKey = 'your_secret

Blogs

Book Recommendations