JWT and OAuth Notes

By technoayan
0views
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
PurposeAuthentication token format.Authorization protocol.
UsageUsed to authenticate users.Used to authorize third-party access.
Token TypeSingle token (JWT).Access token and refresh token.
Stateful/StatelessStateless (self-contained).Can be stateful (requires a server-side session).
Token StorageStored 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."

Show Some Love

Let the author know you enjoyed this content

0
people like this

Sign in to show your appreciation

Share This Post

Help others discover this content

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!