OAuth 2.0 and JWT Authorization in JavaScript: A Complete Guide

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

OAuth 2.0 and JWT Authorization in JavaScript: In Practice

\n\n

Modern web applications rarely do without an authentication and authorization system. The two most popular standards — OAuth 2.0 and JWT (JSON Web Tokens) — are often used together to create secure and scalable solutions. In this article, we will cover how to implement OAuth 2.0 and JWT authorization in JavaScript (Node.js) with practical code examples.

\n\n

This material will be useful for both beginners and experienced developers who want to gain a deeper understanding of how tokens and delegated access work.

\n\n

What are OAuth 2.0 and JWT?

\n\n

OAuth 2.0 is an authorization protocol that allows applications to obtain limited access to user resources without sharing their credentials. For example, you can log into a website via Google or GitHub — that is OAuth 2.0.

\n\n

JWT (JSON Web Token) is a compact token format that contains encoded data (payload) and a signature. JWT is used to transmit information between parties (client and server) and verify its authenticity.

\n\n

In combination, OAuth 2.0 acts as the token issuance protocol, while JWT serves as the format for the access tokens themselves.

\n\n

Server Setup and Dependency Installation

\n\n

First, let's create a simple server on Express.js and install the necessary packages:

\n\n
npm init -y\nnpm install express jsonwebtoken dotenv cors axios\nnpm install --save-dev nodemon
\n\n

Project structure:

\n
    \n
  • server.js — main server file
  • \n
  • .env — environment variables
  • \n
  • middleware/auth.js — middleware for JWT verification
  • \n
  • routes/auth.js — authentication routes
  • \n
\n\n

Implementing JWT Authorization

\n\n

Let's start with basic JWT token generation and verification. Create server.js:

\n\n
const express = require('express');\nconst jwt = require('jsonwebtoken');\nrequire('dotenv').config();\n\nconst app = express();\napp.use(express.json());\n\nconst SECRET_KEY = process.env.JWT_SECRET || 'my_secret_key';\n\n// Token generation\nfunction generateToken(user) {\n  const payload = {\n    id: user.id,\n    email: user.email,\n    role: user.role\n  };\n  return jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });\n}\n\n// Example login route\napp.post('/login', (req, res) => {\n  const { email, password } = req.body;\n  // Database verification should go here\n  const user = { id: 1, email, role: 'user' };\n  const token = generateToken(user);\n  res.json({ token });\n});\n\n// Middleware for token verification\nfunction authenticateToken(req, res, next) {\n  const authHeader = req.headers['authorization'];\n  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN\n\n  if (!token) {\n    return res.status(401).json({ error: 'Token not provided' });\n  }\n\n  jwt.verify(token, SECRET_KEY, (err, user) => {\n    if (err) {\n      return res.status(403).json({ error: 'Invalid token' });\n    }\n    req.user = user;\n    next();\n  });\n}\n\n// Protected route\napp.get('/profile', authenticateToken, (req, res) => {\n  res.json({ message: 'Access granted', user: req.user });\n});\n\napp.listen(3000, () => console.log('Server running on port 3000'));
\n\n

Integrating OAuth 2.0 via Google

\n\n

Now let's add OAuth 2.0 using Google as the provider. Create routes/auth.js:

\n\n
const express = require('express');\nconst axios = require('axios');\nconst jwt = require('jsonwebtoken');\nconst router = express.Router();\n\nconst GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;\nconst GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;\nconst REDIRECT_URI = 'http://localhost:3000/auth/google/callback';\nconst JWT_SECRET = process.env.JWT_SECRET;\n\n// Route for initial                

Blogs

Book Recommendations