MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
OAuth2 and Social Login Integration0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
10.1JWT Authentication Flow and Silent Token Refresh10.2OAuth2 and Social Login Integration10.3Role-Based Access Control (RBAC) and Permission Matrices10.4Securing Client-Side Storage and CSRF / XSS Mitigation
HomeTutorialsReact.js for AdvancedOAuth2 and Social Login Integration
Role-Based Access Control (RBAC) and Permission Matrices

OAuth2 and Social Login Integration

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Enterprise applications frequently delegate identity management to trusted identity providers (Google, GitHub, Microsoft, Okta) via the OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange). PKCE is the gold-standard security protocol for single-page applications where client secrets cannot be securely stored.


1. Why PKCE is Mandatory for SPAs

In traditional OAuth 2.0, the backend uses a client_secret to exchange an authorization code for tokens. Because SPAs run entirely in the browser, any embedded secret is publicly readable via DevTools.

1PKCE Protocol Flow:
21. Client generates high-entropy random string: 'code_verifier'
32. Client hashes verifier via SHA-256: 'code_challenge'
43. Client redirects to IdP: /authorize?code_challenge=xyz&code_challenge_method=S256
54. User logs in at IdP, IdP redirects back with '?code=auth_code_123'
65. Client sends: POST /token { code: auth_code_123, code_verifier: random_string }
76. IdP hashes code_verifier, matches against code_challenge, and issues tokens!

2. Generating PKCE Challenge in TypeScript

1// utils/pkce.ts
2function dec2hex(dec: number) {
3 return ("0" + dec.toString(16)).substr(-2);
4}
5 
6export function generateCodeVerifier(length = 64): string {
7 const array = new Uint8Array(length / 2);
8 window.crypto.getRandomValues(array);
9 return Array.from(array, dec2hex).join("");
10}
11 
12export async function generateCodeChallenge(verifier: string): Promise<string> {
13 const encoder = new TextEncoder();
14 const data = encoder.encode(verifier);
15 const digest = await window.crypto.subtle.digest("SHA-256", data);
16
17 // Base64URL encode
18 return btoa(String.fromCharCode(...new Uint8Array(digest)))
19 .replace(/\+/g, "-")
20 .replace(/\//g, "_")
21 .replace(/=+$/, "");
22}

3. Initiating Social Login (Google / GitHub)

1import React from "react";
2import { generateCodeVerifier, generateCodeChallenge } from "./utils/pkce";
3 
4export function SocialLoginButtons() {
5 const handleOAuthLogin = async (provider: "google" | "github") => {
6 const verifier = generateCodeVerifier();
7 const challenge = await generateCodeChallenge(verifier);
8 
9 // Persist verifier temporarily in sessionStorage for callback verification
10 sessionStorage.setItem("pkce_verifier", verifier);
11 
12 const endpoints = {
13 google: "https://accounts.google.com/o/oauth2/v2/auth",
14 github: "https://github.com/login/oauth/authorize",
15 };
16 
17 const clientIds = {
18 google: "ENTERPRISE_GOOGLE_CLIENT_ID.apps.googleusercontent.com",
19 github: "ENTERPRISE_GITHUB_CLIENT_ID",
20 };
21 
22 const params = new URLSearchParams({
23 client_id: clientIds[provider],
24 redirect_uri: `${window.location.origin}/auth/callback`,
25 response_type: "code",
26 scope: provider === "google" ? "openid profile email" : "read:user user:email",
27 code_challenge: challenge,
28 code_challenge_method: "S256",
29 state: crypto.randomUUID(), // CSRF prevention token
30 });
31 
32 // Redirect user to Identity Provider login page
33 window.location.href = `${endpoints[provider]}?${params.toString()}`;
34 };
35 
36 return (
37 <div className="space-y-3 max-w-sm p-6 bg-slate-900 border border-slate-800 rounded-xl">
38 <h2 className="text-white font-bold text-lg mb-4">Enterprise Single Sign-On</h2>
39 
40 <button
41 onClick={() => handleOAuthLogin("google")}
42 className="w-full py-2.5 px-4 bg-white text-slate-900 font-semibold rounded-lg flex items-center justify-center gap-2 hover:bg-slate-100 transition"
43 >
44 Continue with Google Workspace
45 </button>
46 
47 <button
48 onClick={() => handleOAuthLogin("github")}
49 className="w-full py-2.5 px-4 bg-slate-800 text-white font-semibold rounded-lg flex items-center justify-center gap-2 hover:bg-slate-700 transition"
50 >
51 Continue with GitHub Enterprise
52 </button>
53 </div>
54 );
55}

4. Handling the OAuth Callback in React

1// pages/OAuthCallback.tsx
2import React, { useEffect, useState } from "react";
3import { useNavigate, useSearchParams } from "react-router-dom";
4 
5export function OAuthCallback() {
6 const [searchParams] = useSearchParams();
7 const navigate = useNavigate();
8 const [error, setError] = useState<string | null>(null);
9 
10 useEffect(() => {
11 const code = searchParams.get("code");
12 const verifier = sessionStorage.getItem("pkce_verifier");
13 
14 if (!code || !verifier) {
15 setError("Missing authorization code or PKCE verifier");
16 return;
17 }
18 
19 // Post authorization code and verifier to your application backend
20 fetch("/api/auth/oauth/token", {
21 method: "POST",
22 headers: { "Content-Type": "application/json" },
23 body: JSON.stringify({ code, code_verifier: verifier }),
24 })
25 .then((res) => {
26 if (!res.ok) throw new Error("OAuth token exchange failed");
27 return res.json();
28 })
29 .then((data) => {
30 sessionStorage.removeItem("pkce_verifier");
31 navigate("/dashboard");
32 })
33 .catch((err) => {
34 setError(err.message);
35 });
36 }, [searchParams, navigate]);
37 
38 if (error) {
39 return <div className="p-8 text-rose-400">Authentication Error: {error}</div>;
40 }
41 
42 return (
43 <div className="flex h-screen items-center justify-center bg-slate-950 text-white">
44 <div className="text-center">
45 <div className="animate-spin h-8 w-8 border-4 border-cyan-500 border-t-transparent mx-auto mb-4 rounded-full" />
46 <p className="text-sm font-medium">Finalizing identity verification...</p>
47 </div>
48 </div>
49 );
50}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is OAuth 2.0 PKCE (Proof Key for Code Exchange) mandatory for Single Page Applications?
Question 2
What is the relationship between the code_verifier and code_challenge in PKCE?
Question 3
What is the purpose of the state query parameter in OAuth 2.0 authorization requests?
Question 4
Where should the code_verifier be stored while the browser is redirected to the external Identity Provider?
Question 5
What error occurs if an attacker intercepts the authorization code and attempts to exchange it without the code_verifier?
Next Lesson

Role-Based Access Control (RBAC) and Permission Matrices

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
JWT Authentication Flow and Silent Token RefreshRole-Based Access Control (RBAC) and Permission Matrices

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext