How OAuth Works
June 29, 2025How OAuth Works
OAuth is a protocol that allows third-party applications to access user data without sharing passwords. It's the backbone of secure authorization used by platforms like Google, Twitter, and Facebook.
π What Is OAuth?
OAuth (Open Authorization) enables users to approve an app to act on their behalf without giving away their credentials. For example, you can allow a scheduling app to access your Google Calendar.
π Step 1: Authorization Request
Redirect the user to the authorization server:
const params = {
response_type: 'code',
client_id: 'your-client-id',
redirect_uri: 'https://yourapp.com/callback',
scope: 'email profile',
state: 'secureRandomString'
};
const url = 'https://auth.example.com/oauth/authorize?' + new URLSearchParams(params);
// window.location = url;
π Step 2: Callback with Code
Once the user approves, they'll be redirected with a ?code and ?state.
π οΈ Step 3: Exchange Code for Token
const response = await fetch('https://auth.example.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: 'the-code-from-query',
redirect_uri: 'https://yourapp.com/callback',
client_id: 'your-client-id',
client_secret: 'your-client-secret'
})
});
const data = await response.json();
const accessToken = data.access_token;
π‘ What is PKCE?
PKCE (Proof Key for Code Exchange) is an enhancement for public clients (like mobile apps) that can't store secrets securely.
// Frontend
const codeVerifier = generateRandomString();
const codeChallenge = await sha256(codeVerifier);
sessionStorage.setItem('verifier', codeVerifier);
const params = {
response_type: 'code',
code_challenge_method: 'S256',
code_challenge: codeChallenge
};
π’ Summary
- Use OAuth to authorize apps securely.
- Always verify the state parameter.
- Use PKCE for frontend and mobile apps.
Blog
Jul 07, 2025
Laravel 12.19: Elegant Query Builders with PHP Attributes In Laravelβ―12.19, you can now use the #[UseEloquentBuilder] PHP attribute to assign a cus...
Jul 28, 2025
π What’s New in React Native 0.80? The React Native 0.80 release marks a pivotal moment in mobile development. This update not only enhances...
Aug 17, 2025
Laravel Global Scopes: Automatic Query Filtering Eloquent Importance: Enforce consistent filters across all model queries (e.g., Soft Del...
Aug 09, 2025
Object-Oriented Programming (OOP) is a modern software development approach that divides an application into units called Objects that interact with...
Jul 07, 2025
How to cache report queries with fixed timelines How to generate large reports asynchronously using job queues 1. π§ Report Query Caching wi...
Jul 31, 2025
The useCallback hook in React is used to return a memoized version of a callback function, so it's only recreated when its dependencies change. The...