JWT and OAuth Notes

Loading...
By technoayan
JWTOAuthAuthenticationSecurity
JWT and OAuth Notes
0 min read
Web Security
JWT
OAuth
Authentication
Security

JWT and OAuth Notes

A comprehensive guide to understanding JWT and OAuth, including their workings, differences, and practical examples.

📝 Notes: JWT and OAuth

🛡️ 1. JWT (JSON Web Token)

🔑 What is JWT?

JWT is a compact and self-contained way to represent information between two parties as a JSON object. It's commonly used for authentication and authorization purposes in web applications.

💡 How JWT Works:

  • Header: Contains metadata about the token (e.g., signing algorithm).
  • Payload: Contains claims, or the information you want to transmit (e.g., user info, permissions).
  • Signature: Ensures the token has not been tampered with.

Example of JWT structure:

Header: { "alg": "HS256", "typ": "JWT" } Payload: { "user_id": 123, "role": "admin", "exp": "timestamp" } Signature: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

🔑 JWT Example Code (Node.js):

JAVASCRIPT
const jwt = require('jsonwebtoken');

// Creating a JWT
const token = jwt.sign({ userId: 123, role: 'admin' }, 'your-secret-key', { expiresIn: '1h' });
console.log('JWT:', token);

// Verifying the JWT
jwt.verify(token, 'your-secret-key', (err, decoded) => {
  if (err) {
    console.log('Token is invalid or expired');
  } else {
    console.log('Decoded JWT:', decoded);
  }
});

✅ Advantages of JWT:

  • Stateless: The server does not need to store session data.
  • Compact: Smaller in size, thus reducing overhead.
  • Secure: Can be encrypted and signed.

🔑 2. OAuth (Open Authorization)

🛠️ What is OAuth?

OAuth is an open standard for access delegation commonly used for token-based authentication and authorization in web applications. It allows users to grant third-party services limited access to their resources without sharing their credentials.

💡 How OAuth Works:

  • Authorization Code Grant: The user authorizes the client to access their data.
  • Access Token: The client gets an access token to access resources.
  • Refresh Token: Used to get a new access token when the old one expires.

Example of OAuth flow:

  1. User clicks on "Login with Google" on a website.
  2. Website redirects to Google's OAuth server.
  3. User grants permission to the website to access their Google profile.
  4. Google redirects back with an authorization code.
  5. Website exchanges the code for an access token and refresh token.
  6. Website uses the access token to fetch data from the user's Google profile.

🔑 OAuth Example Code (Node.js with Passport.js):

JAVASCRIPT
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
  clientID: 'your-client-id',
  clientSecret: 'your-client-secret',
  callbackURL: 'http://localhost:3000/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
  console.log('User Profile:', profile);
  return done(null, profile);
}));

// Express route for Google login
app.get('/auth/google', passport.authenticate('google', {
  scope: ['https://www.googleapis.com/auth/plus.login']
}));

// Google callback route
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => {
  res.redirect('/profile');
});

✅ Advantages of OAuth:

  • Delegated Access: Users can share their data without revealing credentials.
  • Granular Permissions: Clients can request limited access, rather than full access.
  • Secure: Avoids sharing passwords by using tokens.

🤔 Difference Between JWT and OAuth

| Feature | JWT | OAuth | |---------------------|-------------------------------------------------|------------------------------------------------| | Purpose | Authentication token format. | Authorization protocol. | | Usage | Used to authenticate users. | Used to authorize third-party access. | | Token Type | Single token (JWT). | Access token and refresh token. | | Stateful/Stateless | Stateless (self-contained). | Can be stateful (requires a server-side session). | | Token Storage | Stored in localStorage, cookies, etc. | Stored by authorization server. |


📊 Conclusion:

  • JWT is a compact, self-contained method for transmitting information between two parties.
  • OAuth is a protocol for authorization that allows users to grant access to third-party services securely without sharing credentials.

Thanks for reading!

technoayan

Author & Tech Enthusiast

"Keep learning, keep growing, and keep sharing knowledge with the world."

Rate This Post

Share your thoughts and help others discover great content

Sign in to rate this post and share your feedback

Community Rating

No ratings yet. Be the first to rate this post!

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!

TechnoBlogs

by Ayan Ahmad

Exploring the world of technology through insightful articles, tutorials, and personal experiences. Join me on this journey of continuous learning and innovation.

Stay Updated

Built With

React
Next.js
Tailwind
Firebase
Powered by Coffee

Every line of code written with love and caffeine ☕

© 2025 TechnoBlogsMade withbyAyan Ahmad

Open source • Privacy focused • Built for developersPrivacy PolicyTerms of Service