OAuth 2.0 and JWT Authorization in TypeScript: 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

OAuth 2.0 and JWT Authorization in TypeScript: for Beginners



Modern web applications rarely do without authentication and authorization mechanisms. The two most popular standards are OAuth 2.0 (an access delegation protocol) and JWT (JSON Web Token, a compact way to transmit data). In this article, we will break down how to implement OAuth 2.0 and JWT authorization in TypeScript by creating a simple but functional server. The material is aimed at beginner developers familiar with the basics of TypeScript and Node.js.



What are OAuth 2.0 and JWT?



Before writing code, it's important to understand the theory.



OAuth 2.0

This is a protocol that allows a user to grant a third-party application limited access to their resources (e.g., their profile on GitHub or Google) without sharing their login and password. OAuth 2.0 has several roles:

  • Resource Owner — the owner of the resource (the user).
  • Client — the application that wants to gain access.
  • Authorization Server — the server that issues tokens after successful authentication.
  • Resource Server — the server that stores protected data.

The most common scenario is the "Authorization Code Flow", where the user is redirected to the provider's page, logs in, and then the server exchanges the received code for a token.



JWT (JSON Web Token)

JWT is a string in the format header.payload.signature that contains data (claims) and is signed with a secret key. It is used as an Access Token (short-lived) or a Refresh Token (long-lived) in OAuth 2.0. The advantage of JWT is that it is self-contained: the server can verify it without querying a database.



Project Setup and Dependency Installation



Let's create a new TypeScript project. Make sure you have Node.js and npm installed.



mkdir oauth-jwt-typescriptcd oauth-jwt-typescriptnpm init -ynpm install express jsonwebtoken dotenv cors cookie-parsernpm install -D typescript @types/node @types/express @types/jsonwebtoken @types/cors @types/cookie-parser ts-node nodemonnpx tsc --init


In the tsconfig.json file, uncomment the line "outDir": "./dist" and set "rootDir": "./src". Create the folder structure:



src/  ├── index.ts  ├── auth.ts  ├── middleware.ts  └── types.ts.env


In the .env file, specify:



ACCESS_TOKEN_SECRET=your-secret-key-123REFRESH_TOKEN_SECRET=your-refresh-secret-456PORT=3000


Implementing the Server with OAuth 2.0 and JWT



1. Basic Server Structure (index.ts)

Let's write a simple Express server with routes for login, token retrieval, and a protected endpoint.



import express from 'express';import cors from 'cors';import cookieParser from 'cookie-parser';import dotenv from 'dotenv';import { login, refresh, logout } from './auth';import { authenticateToken } from './middleware';

dotenv.config();

const app = express();app.use(express.json());app.use(cors());app.use(cookieParser());

// Public routeapp.get('/', (req, res) => { res.send('OAuth 2.0 + JWT Server is running');});

// Authentication (simulating OAuth 2.0)app.post('/login', login);app.post('/token', refresh); // Refresh Access Tokenapp.delete('/logout', logout);

// Protected routeapp.get('/protected', authenticateToken, (req, res) => { res.json({ message: 'Access granted', user: (req as any).user });});

app.listen(process.env.PORT, () => { console.log(`Server running on port ${process.env.PORT}`);});


2. Data Types (types.ts)

export interface TokenPayload {  userId: number;  username: string;}

export int

Blogs

Book Recommendations